protected IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { // Intercept the WM_DEVICECHANGE message if (msg == Dbt.WM_DEVICECHANGE) { // Get the message event type int nEventType = 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(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(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 || nEventType == Dbt.DBT_DEVICEARRIVAL) { //MessageBox.Show("Device \"" + devicePath + "\" was removed"); listCOMPorts(); } } } } return(IntPtr.Zero); }
protected override void WndProc(ref Message m) { try { if (m.Msg == 0x219) { int wParam = m.WParam.ToInt32(); if (wParam == 0x8000) { if (IsDeviceArrivalEnabled) { DDI_HID.instance().open(); DDI_TOOLSTICK.instance().open(); } } else if ((wParam == 0x8004) && IsDeviceRemovalEnabled) { Dbt.DEV_BROADCAST_HDR structure = new Dbt.DEV_BROADCAST_HDR(); Marshal.PtrToStructure(m.LParam, structure); if (structure.dbch_devicetype == 5) { Dbt.DEV_BROADCAST_DEVICEINTERFACE_1 dev_broadcast_deviceinterface_ = new Dbt.DEV_BROADCAST_DEVICEINTERFACE_1(); Marshal.PtrToStructure(m.LParam, dev_broadcast_deviceinterface_); string removedDevicePath = new string(dev_broadcast_deviceinterface_.dbcc_name).Trim(new char[1]); removedDevicePath = removedDevicePath.Substring(0, removedDevicePath.IndexOf('\0')).Trim(); DDI_HID.instance().closeDevice(removedDevicePath); DDI_TOOLSTICK.instance().closeDevice(removedDevicePath); } } } base.WndProc(ref m); } catch (Exception exception) { _log.Error("Error at HID message: " + exception.Message); } }