以下代码可以检测出指定USB设备的插入及移除事件,但如何保持USB在插入的情况下,判断该设备是否存在呢?
using System; using System.Runtime.InteropServices; using System.Windows.Forms; namespace detectUSB { public partial class mainForm : Form { private IntPtr m_hNotifyDevNode; public mainForm() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { Guid dongle = new Guid("4D36E978-E325-11CE-BFC1-08002BE10318"); //dongle RegisterNotification(dongle); } 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; //设置HID到GUID devIF.dbcc_size = Marshal.SizeOf(devIF); devIF.dbcc_devicetype = Dbt.DBT_DEVTYP_DEVICEINTERFACE; devIF.dbcc_reserved = 0; devIF.dbcc_classguid = guid; //为Dll调用分配缓冲区 devIFBuffer = Marshal.AllocHGlobal(devIF.dbcc_size); //复制DevIF到缓冲区 Marshal.StructureToPtr(devIF, devIFBuffer, true); //注册设备通知 m_hNotifyDevNode = Dbt.RegisterDeviceNotification(this.Handle, devIFBuffer, Dbt.DEVICE_NOTIFY_WINDOW_HANDLE); //复制buffer到devIF Marshal.PtrToStructure(devIFBuffer, devIF); //释放buffer Marshal.FreeHGlobal(devIFBuffer); } //反注册notification private void UnregisterNotification() { uint ret = Dbt.UnregisterDeviceNotification(m_hNotifyDevNode); } //覆写WndProc protected override void WndProc(ref Message m) { // 拦截WM_DEVICECHANGE消息 if (m.Msg == Dbt.WM_DEVICECHANGE) { int nEventType = m.WParam.ToInt32(); //获取消息事件类型 //判断设备连接或者断开 if (nEventType == Dbt.DBT_DEVICEARRIVAL || nEventType == Dbt.DBT_DEVICEREMOVECOMPLETE) { Dbt.DEV_BROADCAST_HDR hdr = new Dbt.DEV_BROADCAST_HDR(); //转换 lparam 为 DEV_BROADCAST_HDR 结构 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(); //转换 lparam 为 DEV_BROADCAST_DEVICEINTERFACE 结构 Marshal.PtrToStructure(m.LParam, devIF); //从广播消息获取设备路径 string devicePath = new string(devIF.dbcc_name); //从字符串中删除空终止的数据 int pos = devicePath.IndexOf((char)0); if (pos != -1) devicePath = devicePath.Substring(0, pos); if (nEventType == Dbt.DBT_DEVICEREMOVECOMPLETE) //设备移除 { label1.Text = "Device \"" + devicePath + "\" was removed"; MessageBox.Show("Device \"" + devicePath + "\" was removed"); } else if (nEventType == Dbt.DBT_DEVICEARRIVAL) //设备插入 { label1.Text = "Device \"" + devicePath + "\" arrived"; MessageBox.Show("Device \"" + devicePath + "\" arrived"); } } } } base.WndProc(ref m); } } }