Popular Posts

Monday, January 2, 2012

Register and Unregister Window Handle Process for USB Device

Actually according to MSDN, this WM_DEVICECHANGE sent to all top-level window when there are changes to the device on the PC. However, Windows provides a new mechanism for applications that want to monitor the installation / release of certain types of devices. The mechanism it uses RegisterDeviceNotification () and UnregisterDeviceNotification (). Both functions are available from Windows 2000. 
In the Delphi declaration in Windows.pas unit.
RegisterDeviceNotification function (hRecipient: THandle;NotificationFilter: Pointer;Flags: DWORD):HDEVNOTIFY; stdcall;
UnregisterDeviceNotification function (Handle: HDEVNOTIFY): BOOL;stdcall;
hRecipient is the window handle to send messages WM_DEVICECHANGE. NotificationFilter contains a pointer to a data structure of type DEV_BROADCAST_DEVICEINTERFACE or DEV_BROADCAST_VOLUME. Because we want to monitor is a USB device, DEV_BROADCAST_DEVICEINTERFACE type we use. Fill in the fields of data structures you can see in this code.
Example call to register a USB device notifications.



procedure TUSBDeviceNotifier.InitResources;var _dev:TDevBroadcastDeviceInterface;begin FWndHandle:=AllocateHwnd(WndProc); ZeroMemory(@_dev, sizeOf(TDevBroadcastDeviceInterface)); with _dev do begin dbcc_size:=sizeOf(TDevBroadcastDeviceInterface); dbcc_devicetype:=DBT_DEVTYP_DEVICEINTERFACE; dbcc_reserved:=0; dbcc_classguid:= GUID_DEVINTERFACE_USB_DEVICE; dbcc_name:=0; end; FPtrHandle:=RegisterDeviceNotification(FWndHandle, @_dev, DEVICE_NOTIFY_WINDOW_HANDLE); end;

In the code above we list window to get the relevant notification events related to device configuration changes (DBT_DEVTYP_DEVICEINTERFACE), more specifically the USB device (GUID_DEVINTERFACE_USB_DEVICE). This GUID declaration is as follows:
const
  GUID_DEVINTERFACE_USB_DEVICE:
     TGUID = '{A5DCBF10-6530-11D2-901F-00C04FB951ED}';

Next we let Windows, the window with the handle stored in FWndHandle like to receive notifications when there are events change the USB device. So that Windows knows that FWndHandle contains the window handle, we are content with the Flags parameter DEVICE_NOTIFY_WINDOW_HANDLE.
If calling RegisterDeviceNotification () successful, this function will return the handle that you can use to remove from the notification list when we do not need it. Pass the handle to the function UnregisterDeviceNotification ().

    Technology