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

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

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

Доброго времени суток.
Более менее неактуальные вопросы
foreach (var dInfo in DriveInfo.GetDrives())
            {
                if (dInfo.IsReady && dInfo.DriveType == DriveType.Removable)
                    usbBox1.Items.Add(string.Format("{0} ({1})",
                        (string.IsNullOrEmpty(dInfo.VolumeLabel) ? "Съёмный диск" : dInfo.VolumeLabel),
                        dInfo.Name));using System;
using LibUsbDotNet;
using LibUsbDotNet.Info;
using LibUsbDotNet.Main;
using System.Collections.ObjectModel;
 
namespace Examples
{
    internal class ShowInfo
    {
        public static UsbDevice MyUsbDevice;
 
        public static void Main(string[] args)
        {
           
            // Dump all devices and descriptor information to console output.
            UsbRegDeviceList allDevices = UsbDevice.AllDevices;
            foreach (UsbRegistry usbRegistry in allDevices)
            {
                if (usbRegistry.Open(out MyUsbDevice))
                {
                    Console.WriteLine("WTF");
                    Console.WriteLine(MyUsbDevice.Info.ToString());
                    for (int iConfig = 0; iConfig < MyUsbDevice.Configs.Count; iConfig++)
                    {
                        UsbConfigInfo configInfo = MyUsbDevice.Configs[iConfig];
                        Console.WriteLine(configInfo.ToString());
 
                        ReadOnlyCollection<UsbInterfaceInfo> interfaceList = configInfo.InterfaceInfoList;
                        for (int iInterface = 0; iInterface < interfaceList.Count; iInterface++)
                        {
                            UsbInterfaceInfo interfaceInfo = interfaceList[iInterface];
                            Console.WriteLine(interfaceInfo.ToString());
 
                            ReadOnlyCollection<UsbEndpointInfo> endpointList = interfaceInfo.EndpointInfoList;
                            for (int iEndpoint = 0; iEndpoint < endpointList.Count; iEndpoint++)
                            {
                                Console.WriteLine(endpointList[iEndpoint].ToString());
                            }
                        }
                    }
                }
            }

            // Free usb resources.
            // This is necessary for libusb-1.0 and Linux compatibility.
            UsbDevice.Exit();
 
            // Wait for user input..
            Console.ReadKey();
        }
    }
}if (nEventType == Dbt.DBT_DEVICEARRIVAL ||
                    nEventType == Dbt.DBT_DEVICEREMOVECOMPLETE)Form1.csusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication6
{
    public partial class Form1 : Form
    {
        private IntPtr m_hNotifyDevNode;
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            Guid hidGuid = new Guid("4d1e55b2-f16f-11cf-88cb-001111000030");
            Guid usbXpressGuid = new Guid("3c5e1462-5695-4e18-876b-f3f3d08aaf18");
            Guid cp210xGuid = new Guid("993f7832-6e2d-4a0f-b272-e2c78e74f93e");
            Guid newCP210xGuid = new Guid("a2a39220-39f4-4b88-aecb-3d86a35dc748");
 
            RegisterNotification(hidGuid);
        }
 
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            UnregisterNotification();
        }
 
        private void RegisterNotification(Guid guid)
        {
            Dbt.DEV_BROADCAST_DEVICEINTERFACE devIF = new Dbt.DEV_BROADCAST_DEVICEINTERFACE();
            IntPtr devIFBuffer;
 
            // Set to HID GUID
            devIF.dbcc_size = Marshal.SizeOf(devIF);
            devIF.dbcc_devicetype = Dbt.DBT_DEVTYP_DEVICEINTERFACE;
            devIF.dbcc_reserved = 0;
            devIF.dbcc_classguid = guid;
 
            // Allocate a buffer for DLL call
            devIFBuffer = Marshal.AllocHGlobal(devIF.dbcc_size);
 
            // Copy devIF to buffer
            Marshal.StructureToPtr(devIF, devIFBuffer, true);
 
            // Register for HID device notifications
            m_hNotifyDevNode = Dbt.RegisterDeviceNotification(this.Handle, devIFBuffer, Dbt.DEVICE_NOTIFY_WINDOW_HANDLE);
 
            // Copy buffer to devIF
            Marshal.PtrToStructure(devIFBuffer, devIF);
 
            // Free buffer
            Marshal.FreeHGlobal(devIFBuffer);
        }
 
        // Unregister HID device notification
        private void UnregisterNotification()
        {
            uint ret = Dbt.UnregisterDeviceNotification(m_hNotifyDevNode);
        }
 
        protected override void WndProc(ref Message m)
        {
            // Intercept the WM_DEVICECHANGE message
            if (m.Msg == Dbt.WM_DEVICECHANGE)
            {
                // Get the message event type
                int nEventType = m.WParam.ToInt32();
 
                // Check for devices being connected or disconnected
                if (nEventType == Dbt.DBT_DEVICEARRIVAL ||
                    nEventType == Dbt.DBT_DEVICEREMOVECOMPLETE)
                {
                    Dbt.DEV_BROADCAST_HDR hdr = new Dbt.DEV_BROADCAST_HDR();
 
                    // Convert lparam to DEV_BROADCAST_HDR structure
                    Marshal.PtrToStructure(m.LParam, hdr);
 
                    if (hdr.dbch_devicetype == Dbt.DBT_DEVTYP_DEVICEINTERFACE)
                    {
                        Dbt.DEV_BROADCAST_DEVICEINTERFACE_1 devIF = new Dbt.DEV_BROADCAST_DEVICEINTERFACE_1();
 
                        // Convert lparam to DEV_BROADCAST_DEVICEINTERFACE structure
                        Marshal.PtrToStructure(m.LParam, devIF);
 
                        // Get the device path from the broadcast message
                        string devicePath = new string(devIF.dbcc_name);
 
                        // Remove null-terminated data from the string
                        int pos = devicePath.IndexOf((char)0);
                        if (pos != -1)
                        {
                            devicePath = devicePath.Substring(0, pos);
                        }
 
                        // An HID device was connected or removed
                        if (nEventType == Dbt.DBT_DEVICEREMOVECOMPLETE)
                        {
                            MessageBox.Show("Device "" + devicePath + "" was removed");
                        }
                        else if (nEventType == Dbt.DBT_DEVICEARRIVAL)
                        {
                            MessageBox.Show("Device "" + devicePath + "" arrived");
                        }
                    }
                }
            }
            base.WndProc(ref m);
        }
    }
}Dbt.csusing System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
 
class Dbt
{
    #region Dbt Class - Constants
 
    public const ushort WM_DEVICECHANGE = 0x0219;
    public const ushort DBT_DEVICEARRIVAL = 0x8000;
    public const ushort DBT_DEVICEREMOVECOMPLETE = 0x8004;
    public const ushort DBT_DEVTYP_DEVICEINTERFACE = 0x0005;
    public const int DEVICE_NOTIFY_WINDOW_HANDLE = 0x0000;
 
    #endregion
 
    #region Dbt Class - Device Change Structures
 
    [StructLayout(LayoutKind.Sequential)]
    public class DEV_BROADCAST_DEVICEINTERFACE
    {
        public int dbcc_size;
        public int dbcc_devicetype;
        public int dbcc_reserved;
        public Guid dbcc_classguid;
        public char dbcc_name;
    }
 
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public class DEV_BROADCAST_DEVICEINTERFACE_1
    {
        public int dbcc_size;
        public int dbcc_devicetype;
        public int dbcc_reserved;
        public Guid dbcc_classguid;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 255)]
        public char[] dbcc_name;
    }
 
    [StructLayout(LayoutKind.Sequential)]
    public class DEV_BROADCAST_HDR
    {
        public int dbch_size;
        public int dbch_devicetype;
        public int dbch_reserved;
    }
 
    #endregion
 
    #region DLL Imports
 
    [DllImport("user32.dll", CharSet=CharSet.Auto)]
    public static extern IntPtr RegisterDeviceNotification(IntPtr hRecipient, IntPtr NotificationFilter, uint Flags);
 
    [DllImport("user32.dll")]
    public static extern uint UnregisterDeviceNotification(IntPtr Handle);
    
    #endregion
}

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

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

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

textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
 
namespace App
{    
    public static class Win32: Object
    {
        public const int WM_DEVICECHANGE = 0x0219;
        public const int DEVICE_ARRIVAL = 0x8000;
        public const int DEVICE_REMOVECOMPLETE = 0x8004;
        private const int DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = 0x4;
        private const int DEVTYP_DEVICEINTERFACE = 0x05;
 
        private const int DBT_DEVTYP_DEVICEINTERFACE = 0x00000005;
 
        private const int DBT_DEVTYP_HANDLE = 0x00000006;
 
        private const int DBT_DEVTYP_OEM = 0x00000000;
 
        private const int DBT_DEVTYP_PORT = 0x00000003;
 
        private const int DBT_DEVTYP_VOLUME = 0x00000002;
 
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
        public class DeviceBroadcastInterface
        {
            public int Size;
            public int DeviceType;
            public int Reserved;
            public Guid ClassGuid;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
            public string Name;
        }
 
        [StructLayout(LayoutKind.Sequential)]
        public struct DEV_BROADCAST_HDR
        {
            public uint dbch_Size;
            public uint dbch_DeviceType;
            public uint dbch_Reserved;
        }
 
        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr RegisterDeviceNotification(IntPtr hwnd, DeviceBroadcastInterface oInterface, uint nFlags);
        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool UnregisterDeviceNotification(IntPtr hHandle);
 
        public static IntPtr RegisterForUsbEvents(IntPtr hWnd)
        {
            var oInterfaceIn = new DeviceBroadcastInterface();
            oInterfaceIn.Size = Marshal.SizeOf(oInterfaceIn);
            oInterfaceIn.ClassGuid = Guid.Empty;
            oInterfaceIn.DeviceType = DEVTYP_DEVICEINTERFACE;
            oInterfaceIn.Reserved = 0;
            return RegisterDeviceNotification(hWnd, oInterfaceIn, DEVICE_NOTIFY_ALL_INTERFACE_CLASSES);
        }
 
        public static bool UnregisterForUsbEvents(IntPtr hHandle)
        {
            return UnregisterDeviceNotification(hHandle);
        }
    }
}

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


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

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

6   голосов , оценка 3.833 из 5
Похожие ответы