I want to disable/enable usb and HDMI port whenever my c# wpf (.net Framework 4.7.2) app runs.

Vishal2 Bansal 225 Reputation points
2025-01-15T12:29:34.7333333+00:00

Online resources are not present for above queries.

I want solution for both admin/non-admin user account.

Please help to provide me the solution.

.NET
.NET
Microsoft Technologies based on the .NET software framework.
4,075 questions
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,819 questions
Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,718 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,244 questions
0 comments No comments
{count} votes

Accepted answer
  1. Hongrui Yu-MSFT 4,200 Reputation points Microsoft Vendor
    2025-01-16T03:34:26.5233333+00:00

    Hi, @Vishal2 Bansal. Welcome to Microsoft Q&A. 

    You could get all the devices of your current computer through the following code.

    string query = "SELECT * FROM Win32_PnPEntity";
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
    foreach (ManagementObject device in searcher.Get())
    {
              Console.WriteLine($"Name: {device["Name"]}" + "\n");
    }
    

    These devices correspond to the devices in Device Manager(Control Panel->View by Select Large icons or Small icons->Device Manager).The order may not be consistent.

    Of course, you could also replace Win32_PnPEntity with Win32_VideoController or Win32_USBController for more precise designation.

    Find the device you want to shut down and start shutting down the device by calling ManagementObject.InvokeMethod.

    Start the device

    device.InvokeMethod("Enable", null);
    

    Turn off the device

    device.InvokeMethod("Disable", null);
    

    After execution, you could observe that the status of the device has changed.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.