Список подключенных HID-устройств - C#

Узнай цену своей работы

Формулировка задачи:

Доброго времени суток.
Листинг программы
  1. Более менее неактуальные вопросы
Листинг программы
  1. foreach (var dInfo in DriveInfo.GetDrives())
  2. {
  3. if (dInfo.IsReady && dInfo.DriveType == DriveType.Removable)
  4. usbBox1.Items.Add(string.Format("{0} ({1})",
  5. (string.IsNullOrEmpty(dInfo.VolumeLabel) ? "Съёмный диск" : dInfo.VolumeLabel),
  6. dInfo.Name));using System;
  7. using LibUsbDotNet;
  8. using LibUsbDotNet.Info;
  9. using LibUsbDotNet.Main;
  10. using System.Collections.ObjectModel;
  11. namespace Examples
  12. {
  13. internal class ShowInfo
  14. {
  15. public static UsbDevice MyUsbDevice;
  16. public static void Main(string[] args)
  17. {
  18. // Dump all devices and descriptor information to console output.
  19. UsbRegDeviceList allDevices = UsbDevice.AllDevices;
  20. foreach (UsbRegistry usbRegistry in allDevices)
  21. {
  22. if (usbRegistry.Open(out MyUsbDevice))
  23. {
  24. Console.WriteLine("WTF");
  25. Console.WriteLine(MyUsbDevice.Info.ToString());
  26. for (int iConfig = 0; iConfig < MyUsbDevice.Configs.Count; iConfig++)
  27. {
  28. UsbConfigInfo configInfo = MyUsbDevice.Configs[iConfig];
  29. Console.WriteLine(configInfo.ToString());
  30. ReadOnlyCollection<UsbInterfaceInfo> interfaceList = configInfo.InterfaceInfoList;
  31. for (int iInterface = 0; iInterface < interfaceList.Count; iInterface++)
  32. {
  33. UsbInterfaceInfo interfaceInfo = interfaceList[iInterface];
  34. Console.WriteLine(interfaceInfo.ToString());
  35. ReadOnlyCollection<UsbEndpointInfo> endpointList = interfaceInfo.EndpointInfoList;
  36. for (int iEndpoint = 0; iEndpoint < endpointList.Count; iEndpoint++)
  37. {
  38. Console.WriteLine(endpointList[iEndpoint].ToString());
  39. }
  40. }
  41. }
  42. }
  43. }
  44.  
  45. // Free usb resources.
  46. // This is necessary for libusb-1.0 and Linux compatibility.
  47. UsbDevice.Exit();
  48. // Wait for user input..
  49. Console.ReadKey();
  50. }
  51. }
  52. }if (nEventType == Dbt.DBT_DEVICEARRIVAL ||
  53. nEventType == Dbt.DBT_DEVICEREMOVECOMPLETE)Form1.csusing System;
  54. using System.Collections.Generic;
  55. using System.ComponentModel;
  56. using System.Data;
  57. using System.Drawing;
  58. using System.Linq;
  59. using System.Text;
  60. using System.Threading.Tasks;
  61. using System.Windows.Forms;
  62. using System.Runtime.InteropServices;
  63.  
  64. namespace WindowsFormsApplication6
  65. {
  66. public partial class Form1 : Form
  67. {
  68. private IntPtr m_hNotifyDevNode;
  69. public Form1()
  70. {
  71. InitializeComponent();
  72. }
  73. private void Form1_Load(object sender, EventArgs e)
  74. {
  75. Guid hidGuid = new Guid("4d1e55b2-f16f-11cf-88cb-001111000030");
  76. Guid usbXpressGuid = new Guid("3c5e1462-5695-4e18-876b-f3f3d08aaf18");
  77. Guid cp210xGuid = new Guid("993f7832-6e2d-4a0f-b272-e2c78e74f93e");
  78. Guid newCP210xGuid = new Guid("a2a39220-39f4-4b88-aecb-3d86a35dc748");
  79. RegisterNotification(hidGuid);
  80. }
  81. private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  82. {
  83. UnregisterNotification();
  84. }
  85. private void RegisterNotification(Guid guid)
  86. {
  87. Dbt.DEV_BROADCAST_DEVICEINTERFACE devIF = new Dbt.DEV_BROADCAST_DEVICEINTERFACE();
  88. IntPtr devIFBuffer;
  89. // Set to HID GUID
  90. devIF.dbcc_size = Marshal.SizeOf(devIF);
  91. devIF.dbcc_devicetype = Dbt.DBT_DEVTYP_DEVICEINTERFACE;
  92. devIF.dbcc_reserved = 0;
  93. devIF.dbcc_classguid = guid;
  94. // Allocate a buffer for DLL call
  95. devIFBuffer = Marshal.AllocHGlobal(devIF.dbcc_size);
  96. // Copy devIF to buffer
  97. Marshal.StructureToPtr(devIF, devIFBuffer, true);
  98. // Register for HID device notifications
  99. m_hNotifyDevNode = Dbt.RegisterDeviceNotification(this.Handle, devIFBuffer, Dbt.DEVICE_NOTIFY_WINDOW_HANDLE);
  100. // Copy buffer to devIF
  101. Marshal.PtrToStructure(devIFBuffer, devIF);
  102. // Free buffer
  103. Marshal.FreeHGlobal(devIFBuffer);
  104. }
  105. // Unregister HID device notification
  106. private void UnregisterNotification()
  107. {
  108. uint ret = Dbt.UnregisterDeviceNotification(m_hNotifyDevNode);
  109. }
  110. protected override void WndProc(ref Message m)
  111. {
  112. // Intercept the WM_DEVICECHANGE message
  113. if (m.Msg == Dbt.WM_DEVICECHANGE)
  114. {
  115. // Get the message event type
  116. int nEventType = m.WParam.ToInt32();
  117. // Check for devices being connected or disconnected
  118. if (nEventType == Dbt.DBT_DEVICEARRIVAL ||
  119. nEventType == Dbt.DBT_DEVICEREMOVECOMPLETE)
  120. {
  121. Dbt.DEV_BROADCAST_HDR hdr = new Dbt.DEV_BROADCAST_HDR();
  122. // Convert lparam to DEV_BROADCAST_HDR structure
  123. Marshal.PtrToStructure(m.LParam, hdr);
  124. if (hdr.dbch_devicetype == Dbt.DBT_DEVTYP_DEVICEINTERFACE)
  125. {
  126. Dbt.DEV_BROADCAST_DEVICEINTERFACE_1 devIF = new Dbt.DEV_BROADCAST_DEVICEINTERFACE_1();
  127. // Convert lparam to DEV_BROADCAST_DEVICEINTERFACE structure
  128. Marshal.PtrToStructure(m.LParam, devIF);
  129. // Get the device path from the broadcast message
  130. string devicePath = new string(devIF.dbcc_name);
  131. // Remove null-terminated data from the string
  132. int pos = devicePath.IndexOf((char)0);
  133. if (pos != -1)
  134. {
  135. devicePath = devicePath.Substring(0, pos);
  136. }
  137. // An HID device was connected or removed
  138. if (nEventType == Dbt.DBT_DEVICEREMOVECOMPLETE)
  139. {
  140. MessageBox.Show("Device "" + devicePath + "" was removed");
  141. }
  142. else if (nEventType == Dbt.DBT_DEVICEARRIVAL)
  143. {
  144. MessageBox.Show("Device "" + devicePath + "" arrived");
  145. }
  146. }
  147. }
  148. }
  149. base.WndProc(ref m);
  150. }
  151. }
  152. }Dbt.csusing System;
  153. using System.Collections.Generic;
  154. using System.Text;
  155. using System.Runtime.InteropServices;
  156. class Dbt
  157. {
  158. #region Dbt Class - Constants
  159. public const ushort WM_DEVICECHANGE = 0x0219;
  160. public const ushort DBT_DEVICEARRIVAL = 0x8000;
  161. public const ushort DBT_DEVICEREMOVECOMPLETE = 0x8004;
  162. public const ushort DBT_DEVTYP_DEVICEINTERFACE = 0x0005;
  163. public const int DEVICE_NOTIFY_WINDOW_HANDLE = 0x0000;
  164. #endregion
  165. #region Dbt Class - Device Change Structures
  166. [StructLayout(LayoutKind.Sequential)]
  167. public class DEV_BROADCAST_DEVICEINTERFACE
  168. {
  169. public int dbcc_size;
  170. public int dbcc_devicetype;
  171. public int dbcc_reserved;
  172. public Guid dbcc_classguid;
  173. public char dbcc_name;
  174. }
  175. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  176. public class DEV_BROADCAST_DEVICEINTERFACE_1
  177. {
  178. public int dbcc_size;
  179. public int dbcc_devicetype;
  180. public int dbcc_reserved;
  181. public Guid dbcc_classguid;
  182. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 255)]
  183. public char[] dbcc_name;
  184. }
  185. [StructLayout(LayoutKind.Sequential)]
  186. public class DEV_BROADCAST_HDR
  187. {
  188. public int dbch_size;
  189. public int dbch_devicetype;
  190. public int dbch_reserved;
  191. }
  192. #endregion
  193. #region DLL Imports
  194. [DllImport("user32.dll", CharSet=CharSet.Auto)]
  195. public static extern IntPtr RegisterDeviceNotification(IntPtr hRecipient, IntPtr NotificationFilter, uint Flags);
  196. [DllImport("user32.dll")]
  197. public static extern uint UnregisterDeviceNotification(IntPtr Handle);
  198. #endregion
  199. }

Парюсь уже 4 часа 46 минут

Подскажите хотя-бы как сразу же отключить новое устройство после получения WM_DEVICECHANGE? Тут уж сам найти не могу.
Эхх, сплошной игнор, неужели никто помочь не может? Подскажите как использовать DiUninstallDevice в шарпе?

Решение задачи: «Список подключенных HID-устройств»

textual
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Runtime.InteropServices;
  5.  
  6. namespace App
  7. {    
  8.     public static class Win32: Object
  9.     {
  10.         public const int WM_DEVICECHANGE = 0x0219;
  11.         public const int DEVICE_ARRIVAL = 0x8000;
  12.         public const int DEVICE_REMOVECOMPLETE = 0x8004;
  13.         private const int DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = 0x4;
  14.         private const int DEVTYP_DEVICEINTERFACE = 0x05;
  15.  
  16.         private const int DBT_DEVTYP_DEVICEINTERFACE = 0x00000005;
  17.  
  18.         private const int DBT_DEVTYP_HANDLE = 0x00000006;
  19.  
  20.         private const int DBT_DEVTYP_OEM = 0x00000000;
  21.  
  22.         private const int DBT_DEVTYP_PORT = 0x00000003;
  23.  
  24.         private const int DBT_DEVTYP_VOLUME = 0x00000002;
  25.  
  26.         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
  27.         public class DeviceBroadcastInterface
  28.         {
  29.             public int Size;
  30.             public int DeviceType;
  31.             public int Reserved;
  32.             public Guid ClassGuid;
  33.             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
  34.             public string Name;
  35.         }
  36.  
  37.         [StructLayout(LayoutKind.Sequential)]
  38.         public struct DEV_BROADCAST_HDR
  39.         {
  40.             public uint dbch_Size;
  41.             public uint dbch_DeviceType;
  42.             public uint dbch_Reserved;
  43.         }
  44.  
  45.         [DllImport("user32.dll", SetLastError = true)]
  46.         private static extern IntPtr RegisterDeviceNotification(IntPtr hwnd, DeviceBroadcastInterface oInterface, uint nFlags);
  47.         [DllImport("user32.dll", SetLastError = true)]
  48.         private static extern bool UnregisterDeviceNotification(IntPtr hHandle);
  49.  
  50.         public static IntPtr RegisterForUsbEvents(IntPtr hWnd)
  51.         {
  52.             var oInterfaceIn = new DeviceBroadcastInterface();
  53.             oInterfaceIn.Size = Marshal.SizeOf(oInterfaceIn);
  54.             oInterfaceIn.ClassGuid = Guid.Empty;
  55.             oInterfaceIn.DeviceType = DEVTYP_DEVICEINTERFACE;
  56.             oInterfaceIn.Reserved = 0;
  57.             return RegisterDeviceNotification(hWnd, oInterfaceIn, DEVICE_NOTIFY_ALL_INTERFACE_CLASSES);
  58.         }
  59.  
  60.         public static bool UnregisterForUsbEvents(IntPtr hHandle)
  61.         {
  62.             return UnregisterDeviceNotification(hHandle);
  63.         }
  64.     }
  65. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

6   голосов , оценка 3.833 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы