How to Detect USB Drive Insertion and Removal

How can i detect when a user inserted or removed a USB thumb drive?

An application can use the RequestDeviceNotification API to get notified by the system as soon as a USB device is inserted or removed.

To avoid getting unwanted notifications, they can be filtered. For mass-storage devices, the filter GUID to use in this case is BLOCK_DRIVER_GUID.
The notifications will be delivered on a message queue that needs to be allocated in advance.

The sample code below omits error checking to keep the code more readable.

#include "storemgr.h"  // contains the definition of BLOCK_DRIVER_GUID

union tDevDetail
    DEVDETAIL DevDetail;
    BYTE byBuffer[sizeof(DEVDETAIL) + MAX_DEVCLASS_NAMELEN * sizeof(TCHAR)];

    HANDLE          msgqueuehandle;
    GUID            blockguid;
    tDevDetail      buf;
    DWORD           flags = 0;
    DWORD           readt = 0;

    // Setup Message Queue
    memset(&msgopts, 0, sizeof(msgopts));
    msgopts.dwSize        = sizeof(msgopts);
    msgopts.dwFlags       = 0;
    msgopts.dwMaxMessages = 0;
    msgopts.cbMaxMessage  = sizeof(tDevDetail);
    msgopts.bReadAccess   = TRUE;
    msgqueuehandle        = CreateMsgQueue(NULL, &msgopts);

    // Setup Device Notification
    memcpy(&blockguid, &BLOCK_DRIVER_GUID, sizeof(GUID));
    HANDLE nothandle = RequestDeviceNotifications(&blockguid, msgqueuehandle, TRUE);

    // Wait for a device notification for an infinite time
    ReadMsgQueue(msgqueuehandle, &buf, sizeof(tDevDetail), &readt, INFINITE, &flags);
  • buf.DevDetail.fAttached indicates whether a device was inserted or removed
  • buf.DevDetail.szName indicates the type of connected device (SD card, USB disk, …)

Please note that the notification is sent very early, as soon as the device is recognized, It might well be required to add some delay (and retry algorithm) before the filesystem is accessible.