Detect removable devices in Winforms

Windows sends a WM_DEVICECHANGE message when devices changes, with WParam equals DBT_DEVICEARRIVAL or DBT_DBT_DEVICEREMOVECOMPLETE.
These two values works for both CD-ROM and USB.

To monitor, just override WndProc:

protected override void WndProc(ref Message m)
{
    #region Removable devices detection

    const int WM_DEVICECHANGE = 0x219;
    const int DBT_DEVICEARRIVAL = 0x8000;
    const int DBT_CONFIGCHANGECANCELED = 0x19;
    const int DBT_CONFIGCHANGED = 0x18;
    const int DBT_CUSTOMEVENT = 0x8006;
    const int DBT_DEVICEQUERYREMOVE = 0x8001;
    const int DBT_DEVICEQUERYREMOVEFAILED = 0x8002;
    const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
    const int DBT_DEVICEREMOVEPENDING = 0x8003;
    const int DBT_DEVICETYPESPECIFIC = 0x8005;
    const int DBT_DEVNODES_CHANGED = 0x7;
    const int DBT_QUERYCHANGECONFIG = 0x17;
    const int DBT_USERDEFINED = 0xFFFF;

    if ( m.Msg == WM_DEVICECHANGE )
    {
        switch ( (int)( m.WParam ) )
        {
            case WM_DEVICECHANGE:
            case DBT_DEVICEARRIVAL:
                // CD-ROM / USB inserted
                // driveUpdater.RunWorkerAsync();
                break;
            case DBT_CONFIGCHANGECANCELED:
            case DBT_CONFIGCHANGED:
            case DBT_CUSTOMEVENT:
            case DBT_DEVICEQUERYREMOVE:
            case DBT_DEVICEQUERYREMOVEFAILED:
            case DBT_DEVICEREMOVECOMPLETE:
                // CD-ROM / USB removed
                // driveUpdater.RunWorkerAsync();
                break;
            case DBT_DEVICEREMOVEPENDING:
            case DBT_DEVICETYPESPECIFIC:
            case DBT_DEVNODES_CHANGED:
            case DBT_QUERYCHANGECONFIG:
            case DBT_USERDEFINED:
            default:
                break;
        }
    }

    #endregion

    base.WndProc(ref m);
}

Detect removable devices in Winforms
https://blog.bigpower.dev/Detect-removable-devices-in-Winforms/
Author
Paul Chen
Posted on
May 2, 2008
Licensed under