Use devcon.exe to control USB devices

Source: Internet
Author: User

Three days ago, when chatting with Shuo Ge, he sent me an interesting program-control USB device plugging. At that time, I saw the I/O processing of cookbook, and I thought it was definitely a hand (BS ). The next day, I started to follow the cookbook:

 private void InitUsbDrives() {    DriveInfo[] allDrives = DriveInfo.GetDrives();    foreach (DriveInfo d in allDrives)    {                if (d.DriveType == DriveType.Removable)                {                    listUsbDrives.Items.Add(d.Name);                }     }}

The result is not displayed. That's strange. Why? Originally, the getdrives () method only obtains the logical drive letter. I didn't insert a USB flash drive into my computer at the time, but of course it didn't show up. The program sent to me by Shuo Ge shows all USB interfaces. Then I will search for the I/O namespace on msdn, but there is nothing to gain. I had to ask Google for help. I checked all USB ports, listened to USB ports, listened to USB ports, and found all USB-related ports. One of the most popular USB interfaces is written on the Internet, but there is no substantive content. Of course, some results are still found. For example, there are many listening methods:

Public const int wm_devicechange = 0x219; Public const int dbt_devicearrival = 0x8000; Public const int dbt_configchangecanceled = 0x0019; Public const int dbt_configchanged = 0x0018; public const int dbt_customevent = 0x8006; Public const int dbt_devicequeryremove = 0x8001; Public const int encrypted = 0x8002; Public const int dbt_deviceremovecomplete = 0x8004; Public const int d Bt_deviceremovepending = 0x8003; Public const int dbt_devicetypespecific = 0x8005; Public const int dbt_devnodes_changed = 0x0007; Public const int dbt_querychangeconfig = 0x0017; public const int dbt_userdefined = 0 xFFFF; protected override void wndproc (ref message m) {try {If (M. MSG = wm_devicechange) {Switch (M. wparam. toint32 () {Case wm_devicechange: break; Case dbt_devicearrival: // U disk with T inserted His. timer1.enabled = true; driveinfo [] S = driveinfo. getdrives (); foreach (driveinfo drivei in S) {If (drivei. drivetype = drivetype. removable) {// ls. show (); // This. hide (); // MessageBox. show ("Sss"); break;} int devtype = marshal. readint32 (M. lparam, 4); If (devtype = dbt_devtyp_volume) {dev_broadcast_volume vol; Vol = (dev_broadcast_volume) Marshal. ptrtostructure (M. lparam, typeof (dev_broadca St_volume); Id = vol. dbcv_unitmask.tostring ("X"); this. TEXT = io (ID); this. tag = io (ID); // If (item. length = 0 | io (ID )! = This. tag. tostring () // {//} This. label1.text = This. text;} break; Case dbt_configchangecanceled: break; Case dbt_configchanged: break; Case dbt_customevent: break; Case dbt_devicequeryremove: break; case when: break; Case dbt_deviceremovecomplete: // detach the USB flash drive driveinfo [] I = driveinfo. getdrives (); foreach (driveinfo drinfo in I) {int devtype = marshal. readint32 (M. lparam, 4); If (devtype = dbt_devtyp_volume) {dev_broadcast_volume vol; Vol = (dev_broadcast_volume) Marshal. ptrtostructure (M. lparam, typeof (dev_broadcast_volume); Id = vol. dbcv_unitmask.tostring ("X"); this. TEXT = io (ID) + "disk exited! \ N ";} This. label1.text + = This. text; // MessageBox. show ("the USB flash drive has been uninstalled", "message prompt", messageboxbuttons. OK, messageboxicon. information) ;}break; case when: break; Case dbt_devicetypespecific: break; Case dbt_devnodes_changed: break; Case dbt_querychangeconfig: break; Case dbt_userdefined: break; default: break ;}}} catch (exception ex) {Throw new exception (ex. message);} base. wndproc (ref m );}

This code has several versions, but it is roughly the same. It is to rewrite wndproc (ref message m), determine whether the input message is a USB flash drive, and then display the drive letter at this time. A better version can be enabled.
And disable the USB port. But this is not what I need. Continue searching. Find some useful information in the csdn question:

string[] comPorts = System.IO.Ports.SerialPort.GetPortNames();foreach(string s in comPorts){   listUsbDrives.Items.Add(s);}

 

 

The results of COM1 and com2 are displayed, and the self-feeling is not far from the truth. SerialPort is a serial port consciousness. Is there a USB port? I was excited to check msdn and the result was disappointing.
Does not exist! And the only one is SerialPort. But it provides me with the idea that USB is the physical port of the computer. Can I check the computer information? Is this class available for me to view?
Yes, system. Management. However, if you are not familiar with it, Google will be available. The general usage is as follows:

 

Private managementclass MC; private managementobjectcollection MOC; private void initusbdrives () {MC = new managementclass ("win32_usbcontroller"); MOC = MC. getinstances (); string usbinfo = string. empty; foreach (managementobject Mo in MoC) {foreach (propertydata PD in Mo. properties) {If (PD. name. equals ("DeviceID") {usbinfo = PD. value + "\ n";} If (PD. name. equals ("manufacturer") {usbinfo = usbinfo + "vendor:" + PD. value + "\ n";} else if (PD. name. equals ("name") {usbinfo = usbinfo + "USB controller name:" + PD. value + "\ n";} else if (PD. name. equals ("status") {usbinfo = usbinfo + "USB status:" + PD. value + "\ n";} else if (PD. name. equals ("pnpdeviceid") {usbinfo = usbinfo + "USB controller ID:" + PD. value ;}} listusbdrives. items. add (usbinfo );}}

 

However, it cannot be displayed as I want, and I feel that it is definitely related to win32_usbcontroller, so proceed to msdn. Check the function change:
The http://msdn.microsoft.com/en-us/library/aa394504 (vs.85). aspx
Only English is available. Try the possible parameters again. I plan to write it. At this moment ~ I noticed that Shuo Ge sent my RAR
There is a devcon.exe. What is this? So I checked my program with reflector. I found that I really called this stuff. I went on to Google and found that this tool is very useful.
Devcon help documentation: http://hapeacock.blog.51cto.com/193534/86899
Devcon device enable and disable: http://www.clxp.net.cn/article.asp? Id = 443
In C # cookbook I/O, there is good command line interaction. So, it's very late, so I went to bed. Lying in bed, I was wondering, what should I do? Continue to work after the next day:

The first is the CMD call:
public static string RunProcessCmd(string command)        {            Process application = new Process();            application.StartInfo.FileName = @"cmd.exe";            application.StartInfo.Arguments = "/c" + command;            application.StartInfo.RedirectStandardInput = true;            application.StartInfo.RedirectStandardOutput = true;            application.StartInfo.UseShellExecute = false;            application.StartInfo.CreateNoWindow = true;            application.Start();            application.StandardInput.WriteLine("exit");            string str = application.StandardOutput.ReadToEnd();            application.Close();            return str;        }

Run devcon:

 private void InitUsbDrives()        {            string[] drives = Regex.Split(RunProcessCmd("devcon.exe status usb*"), "\\.\r\n");            listUsbDrives.Items.Clear();            int index = 1;            foreach (string s in drives)            {                string[] strDives = Regex.Split(s, "   ");                if (strDives.Length == 3)                {                    Drives _drives = new Drives()                                         {                                             ID = strDives[0],                                             Name = index + ": " + strDives[1].Substring(6),                                             Status = strDives[2]                                         };                    listUsbDrives.Items.Add(_drives);                }                            }

After some twists and turns, it was done. Previous figure:

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.