Click here to Skip to main content
15,173,506 members
Articles / Programming Languages / C++
Posted 19 Jun 2006


331 bookmarked

Detecting Hardware Insertion and/or Removal

Rate me:
Please Sign up or sign in to vote.
4.88/5 (85 votes)
19 Jun 20066 min read
A user-mode application to detect hardware add/remove with WM_DEVICECHANGE and RegisterDeviceNotification()

Sample Image - HwDetect.png


Hot-pluggable device is now a big threat to IT security. In this article, we will try to develop a user-mode application to detect device change on the system, i.e. plug-in a USB drive, iPod, USB wireless network card, etc. The program can also disable any newly plugged devices. We will get a basic idea on how this works and talk about its limitations at the end of this article.

How to detect hardware change?

Well, in fact, Windows OS will post WM_DEVICECHANGE upon device change. All we need to do is to add a handler to handle this event.

    // ... other handlers

LRESULT CHWDetectDlg::OnMyDeviceChange(WPARAM wParam, LPARAM lParam)
    // for more information, see MSDN help of WM_DEVICECHANGE
    // this part should not be very difficult to understand
        switch( pHdr->dbch_devicetype ) {
                // do something...

            case DBT_DEVTYP_HANDLE:
                // do something...

            case DBT_DEVTYP_OEM:
                PDEV_BROADCAST_OEM pDevOem = (PDEV_BROADCAST_OEM)pHdr;
                // do something...

            case DBT_DEVTYP_PORT:
                // do something...

            case DBT_DEVTYP_VOLUME:
                // do something...
    return 0;

However, by default, Windows OS will only post WM_DEVICECHANGE to

  1. All applications with a top-level window, and
  2. Only upon port and volume change.
Well, this is not bad, since at least you will know when an extra "disk" is mounted/unmounted, and you can get the affected drive letter by using the DEV_BROADCAST_VOLUME.dbcv_unitmask. The downside is that you won't know what physical device has actually been plugged into the system.

API: RegisterDeviceNotification()

To get notified on other types of device changes, or to get notified if you are running as a service and don't have a top-level window, you have to call RegisterDeviceNotification() API. For example, to get notified upon interface change, you can do the following.

2.  ZeroMemory( &NotificationFilter, sizeof(NotificationFilter) );
3.  NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
4.  NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
5.  // assume we want to be notified with USBSTOR
6.  // to get notified with all interface on XP or above
7.  // ORed 3rd param with DEVICE_NOTIFY_ALL_INTERFACE_CLASSES and dbcc_classguid will be ignored
8.  NotificationFilter.dbcc_classguid = GUID_DEVINTERFACE_USBSTOR;
9.  HDEVNOTIFY hDevNotify = RegisterDeviceNotification(this->GetSafeHwnd(),
        amp;NotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE);
10. if( !hDevNotify ) {
11.     // error handling...
12.     return FALSE;
13. }

Pay extra attention to line 8, the NotificationFilter.dbcc_classguid. See Doron Holan's blog

A PnP device is typically associated with two different GUIDs, a device interface GUID and a device class GUID.

A device class GUID defines a broad category of devices. If you open up device manager, the default view is "by type." Each type is a device class, where each class is uniquely ID's by the device class GUID. A device class GUID defines the icon for the class, default security settings, install properties (like a user cannot manually install an instance of this class, it must be enumerated by PNP), and other settings. The device class GUID does not define an I/O interface (see Glossary), rather think of it as a grouping of devices. I think a good clarifying example is the Ports class. Both COM and LPT devices are a part of the Ports class, yet each has its own distinct I/O interface which are not compatible with each other. A device can only belong to one device class. The device class GUID is the GUID you see at the top of an INF file.

A device interface GUID defines a particular I/O interface contract. It is expected that every instanceof the interface GUID will support the same basic set of I/Os. The device interface GUID is what the driver will register and enable/disable based on PnP state. A device can register many device interfaces for itself, it is not limited to one interface GUID. If need be, the device can even register multiple instances of the same GUID (assuming each have their own ReferenceString), although I have never seen a real world need for this. A simple I/O interface contract is the keyboard device interface to the raw input thread. Here is the keyboard device contract that each instance of the keyboard device interface GUID must support.

You can see the current list of device classes and device interface classes at the following registries:

  • \\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class
  • \\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\DeviceClasses

A list of common device interface class GUIDs is given below:

Device Interface NameGUID
USB Raw Device{a5dcbf10-6530-11d2-901f-00c04fb951ed}
Disk Device{53f56307-b6bf-11d0-94f2-00a0c91efb8b}
Network Card{ad498944-762f-11d0-8dcb-00c04fc3358c}
Human Interface Device (HID){4d1e55b2-f16f-11cf-88cb-001111000030}


Let's change our handler code OnMyDeviceChange() as follows:

LRESULT CHWDetectDlg::OnMyDeviceChange(WPARAM wParam, LPARAM lParam)
        switch( pHdr->dbch_devicetype )
                UpdateDevice(pDevInf, wParam);

And from MSDN, we know

    DWORD dbcc_size;
    DWORD dbcc_devicetype;
    DWORD dbcc_reserved;
    GUID dbcc_classguid;
    TCHAR dbcc_name[1];

It seems by using the dbcc_name, we can know what device has been plugged into the system. Sadly, the answer is NO, dbcc_name is for OS internal use and is an identity, it is not human readable. A sample of dbcc_name is as follows:


  • \\?\USB: USB means this is a USB device class
  • Vid_04e8&Pid_053b: Vid/Pid is VendorID and ProductID (but this is device class specific, USB use Vid/Pid, different device classes use different naming conventions)
  • 002F9A9828E0F06: seems to be a unique ID (not sure about how this got generated)
  • {a5dcbf10-6530-11d2-901f-00c04fb951ed}: the device interface class GUID

Now, by using this decoded information, we can get the device description or device friendly name by two methods:

  1. Read the registry directly: for our example dbcc_name, it will be, \\HKLM\SYSTEM\CurrentControlSet\Enum\USB\Vid_04e8&Pid_503b\0002F9A9828E0F06
  2. Use SetupDiXxx

API: SetupDiXxx()

Windows has a set of API to allow an application to retrieve hardware device information programmatically. For example, we can get the device description or device friendly name with the dbcc_name. The flow of the program is roughly as follows:

  1. Use SetupDiGetClassDevs() to get a handle of device info set HDEVINFO, you can think of the handle as a directory handle.
  2. Use SetupDiEnumDeviceInfo() to enumerate all the device in the info set, you can think of this operation as a directory listing. Upon each iteration, we will get a SP_DEVINFO_DATA, you can think of this handle as the file handle.
  3. During the enumeration, use SetupDiGetDeviceInstanceId() to read the instance ID for each device, you can think of this operation as reading file attribute. The instance ID is in the form of "USB\Vid_04e8&Pid_503b\0002F9A9828E0F06", very similar to the dbcc_name.
  4. If the instance ID match the dbcc_name, we call SetupDiGetDeviceRegistryProperty() to retrieve the description or friendly name

The program is listed as follows:

    // dbcc_name:
    // \\?\USB#Vid_04e8&Pid_503b#0002F9A9828E0F06#{a5dcbf10-6530-11d2-901f-00c04fb951ed}
    // convert to
    // USB\Vid_04e8&Pid_503b\0002F9A9828E0F06
    ASSERT(lstrlen(pDevInf->dbcc_name) > 4);
    CString szDevId = pDevInf->dbcc_name+4;
    int idx = szDevId.ReverseFind(_T('#'));
    ASSERT( -1 != idx );
    szDevId.Replace(_T('#'), _T('\\'));

    CString szClass;
    idx = szDevId.Find(_T('\\'));
    ASSERT(-1 != idx );
    szClass = szDevId.Left(idx);

    // if we are adding device, we only need present devices
    // otherwise, we need all devices
    DWORD dwFlag = DBT_DEVICEARRIVAL != wParam
    HDEVINFO hDevInfo = SetupDiGetClassDevs(NULL, szClass, NULL, dwFlag);
    if( INVALID_HANDLE_VALUE == hDevInfo )
        AfxMessageBox(CString("SetupDiGetClassDevs(): ")
            + _com_error(GetLastError()).ErrorMessage(), MB_ICONEXCLAMATION);

    SP_DEVINFO_DATA* pspDevInfoData =
        (SP_DEVINFO_DATA*)HeapAlloc(GetProcessHeap(), 0, sizeof(SP_DEVINFO_DATA));
    pspDevInfoData->cbSize = sizeof(SP_DEVINFO_DATA);
    for(int i=0; SetupDiEnumDeviceInfo(hDevInfo,i,pspDevInfoData); i++)
        DWORD DataT ;
        DWORD nSize=0 ;
        TCHAR buf[MAX_PATH];

        if ( !SetupDiGetDeviceInstanceId(hDevInfo, pspDevInfoData, buf, sizeof(buf), &nSize) )
            AfxMessageBox(CString("SetupDiGetDeviceInstanceId(): ")
                + _com_error(GetLastError()).ErrorMessage(), MB_ICONEXCLAMATION);

        if ( szDevId == buf )
            // device found
            if ( SetupDiGetDeviceRegistryProperty(hDevInfo, pspDevInfoData,
                SPDRP_FRIENDLYNAME, &DataT, (PBYTE)buf, sizeof(buf), &nSize) ) {
                // do nothing
            } else if ( SetupDiGetDeviceRegistryProperty(hDevInfo, pspDevInfoData,
                SPDRP_DEVICEDESC, &DataT, (PBYTE)buf, sizeof(buf), &nSize) ) {
                // do nothing
            } else {
                lstrcpy(buf, _T("Unknown"));
            // update UI
            // .....
            // .....

    if ( pspDevInfoData ) HeapFree(GetProcessHeap(), 0, pspDevInfoData);

Disable a device

Suppose you have the correct HDEVINFO and SP_DEVINFO_DATA (actually, we save the dbcc_name as the tree node extra data and retrieve that data when we right click on the device icon and then call SetupDiGetClassDevs and SetupDiEnumDevicInfo), the flow to disable a device is as follows:

  1. Setup the SP_PROPCHANGE_PARAMS structure properly
  2. Call SetupDiSetClassInstallParams() and pass-in the SP_PROPCHANGE_PARAMS structure
  3. Call SetupDiCallClassInstaller() with DIF_PROPERTYCHANGE

In fact, the DIF codes are a bit complicated, and you will have to call SetupDiSetClassInstallParams() with different structures for different DIF codes. For more information, see MSDN "Handling DIF Codes".

spPropChangeParams.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
spPropChangeParams.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE ;
spPropChangeParams.Scope = DICS_FLAG_GLOBAL ;
spPropChangeParams.HwProfile = 0; // current hardware profile
spPropChangeParams.StateChange = DICS_DISABLE

if( !SetupDiSetClassInstallParams(hDevInfo, &spDevInfoData,
    // note we pass spPropChangeParams as SP_CLASSINSTALL_HEADER
    // but set the size as sizeof(SP_PROPCHANGE_PARAMS)
    // handle error
else if(!SetupDiCallClassInstaller(DIF_PROPERTYCHANGE, hDevInfo, &spDevInfoData))
    // handle error
    // ok, show disable success dialog
    // note, after that, the OS will post DBT_DEVICEREMOVECOMPLETE for the disabled device

Minor Issue

I experience multiple DBT_DEVICEARRIVAL/DBT_DEVICEREMOVECOMPLETE messages on the same insertion/removal of my USB wireless card.


  1. Obviously, the program can only detect device changes when the application is running, e.g. device plugged in before the system power-up, or before the application starts up will not be detected. But this can be solved by saving the current state at a remote computer and then checking the difference during application starts up.
  2. We can disable the device, but that is all we can do. We can't access control the device against the logon user, nor we can provide read only access. IMHO, I think this can only be fixed if we re-implement the whole program as a kernel mode filter driver.


  • June 19th, 2006: Initial release


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Sam NG
Hong Kong Hong Kong
No Biography provided

Comments and Discussions

Questiondisable device is not work in window 10 x64 system ? Pin
Member 1477278614-May-20 15:18
MemberMember 1477278614-May-20 15:18 
QuestionLicenses Pin
Member 1346337815-Oct-17 20:01
MemberMember 1346337815-Oct-17 20:01 
QuestionHow to compile your application in MS VS 2013? There are 58 errors. Pin
Eugene_Buzin19-May-15 3:06
MemberEugene_Buzin19-May-15 3:06 
AnswerRe: How to compile your application in MS VS 2013? There are 58 errors. Pin
jo le serb10-Oct-15 0:00
Memberjo le serb10-Oct-15 0:00 
Questionscm library uses some concepts explained here Pin
victor29662127-Mar-15 4:43
Membervictor29662127-Mar-15 4:43 
QuestionRead/Write data from usb Pin
AshwinK44-Jul-14 20:52
professionalAshwinK44-Jul-14 20:52 
QuestionRegarding C# project Pin
vinayagashiva12317-Jun-14 20:45
Membervinayagashiva12317-Jun-14 20:45 
AnswerRe: Regarding C# project Pin
tha_specializt2-Sep-14 1:16
Membertha_specializt2-Sep-14 1:16 
QuestionHow recognize & separate printer devices Pin
Majid Darab16-May-14 1:54
MemberMajid Darab16-May-14 1:54 
QuestionGood article Pin
pataoengineer29-May-12 18:36
Memberpataoengineer29-May-12 18:36 
QuestionImprovement by log file Pin
Member 833465722-Oct-11 0:37
MemberMember 833465722-Oct-11 0:37 
GeneralMy vote of 4 Pin
Adam Roderick J30-Nov-10 23:42
MemberAdam Roderick J30-Nov-10 23:42 
GeneralDetection USB device connected/disconnected to the computer. Pin
LukeFromCracow4-Feb-10 1:49
MemberLukeFromCracow4-Feb-10 1:49 
Questionproviding read only access Pin
Amit Vilas Shinde18-Dec-09 4:40
MemberAmit Vilas Shinde18-Dec-09 4:40 
GeneralThis demo program NOT will start under Windows 7 Pin
passionfly13-Nov-09 5:51
Memberpassionfly13-Nov-09 5:51 
GeneralRe: This demo program NOT will start under Windows 7 Pin
passionfly130-Nov-09 5:54
Memberpassionfly130-Nov-09 5:54 
AnswerRe: This demo program NOT will start under Windows 7 Pin
M0tah4-Jun-13 10:53
MemberM0tah4-Jun-13 10:53 
GeneralLicense Pin
wsnyder623-Sep-09 5:38
Memberwsnyder623-Sep-09 5:38 
GeneralRe: License Pin
Sam NG23-Sep-09 15:11
MemberSam NG23-Sep-09 15:11 
GeneralRe: License Pin
coolshou15-Nov-21 21:21
Membercoolshou15-Nov-21 21:21 
GeneralPLZ..!!! help me... urgent Pin
fana_rb10-Sep-09 22:08
Memberfana_rb10-Sep-09 22:08 
QuestionHow do I use Button to activate USB device ? Pin
anakecil1-Sep-09 17:51
Memberanakecil1-Sep-09 17:51 
AnswerRe: How do I use Button to activate USB device ? Pin
fana_rb10-Sep-09 22:12
Memberfana_rb10-Sep-09 22:12 
GeneralRe: How do I use Button to activate USB device ? Pin
anakecil10-Sep-09 23:00
Memberanakecil10-Sep-09 23:00 
QuestionHow do I get the drive letter for a USB drive? Pin
tommygr20-Aug-09 15:55
Membertommygr20-Aug-09 15:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.