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((new WindowInteropHelper(this)).Handle, devIFBuffer, Dbt.DEVICE_NOTIFY_WINDOW_HANDLE); // Copy buffer to devIF Marshal.PtrToStructure(devIFBuffer, devIF); // Free buffer Marshal.FreeHGlobal(devIFBuffer); }
private void WndProcClient_MessageReceived(object?sender, WndProcClient.WindowMessage e) { Console.WriteLine(e); switch (e.Msg) { case WndProcClient.WindowsMessage.WM_DEVICECHANGE: Dbt subId = (Dbt)e.wParam.ToInt64(); if (subId == Dbt.CustomEvent || subId == Dbt.DeviceArrival || subId == Dbt.DeviceQueryRemove || subId == Dbt.DeviceQueryRemoveFailed || subId == Dbt.DeviceRemoveComplete || subId == Dbt.DeviceRemovePending || subId == Dbt.DeviceTypeSpecific) { DoBroadcastHdr(e); } break; } }
}//class Form //-- void HandleMessage(ref Message m) { WindowMessageId msgId = (WindowMessageId)m.Msg; if (msgId == WindowMessageId.DeviceChange) { Dbt subId = (Dbt)m.WParam; if (subId == Dbt.CustomEvent || subId == Dbt.DeviceArrival || subId == Dbt.DeviceQueryRemove || subId == Dbt.DeviceQueryRemoveFailed || subId == Dbt.DeviceRemoveComplete || subId == Dbt.DeviceRemovePending || subId == Dbt.DeviceTypeSpecific) { DoBroadcastHdr(m); } } else if (msgId == WindowMessageId.ActivateApp) { } }
// Unregister HID device notification private void UnregisterNotification() { uint ret = Dbt.UnregisterDeviceNotification(m_hNotifyDevNode); }