Detecting Inserted USB Drive - Windows Service

I am trying to detect a USB disk inserted into a windows service, I did it like a normal windows application. The problem is the following code doesn't work for volumes.

Registering device notification:

    DEV_BROADCAST_DEVICEINTERFACE notificationFilter;
    HDEVNOTIFY hDeviceNotify = NULL;        

    ::ZeroMemory(&notificationFilter, sizeof(notificationFilter));

    notificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
    notificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
    notificationFilter.dbcc_classguid = ::GUID_DEVINTERFACE_VOLUME;

    hDeviceNotify = ::RegisterDeviceNotification(g_serviceStatusHandle, &notificationFilter, DEVICE_NOTIFY_SERVICE_HANDLE);

      

Code from ServiceControlHandlerEx function:

case SERVICE_CONTROL_DEVICEEVENT:
    PDEV_BROADCAST_HDR pBroadcastHdr = (PDEV_BROADCAST_HDR)lpEventData;

    switch (dwEventType)
    {
    case DBT_DEVICEARRIVAL:
        ::MessageBox(NULL, "A Device has been plugged in.", "Pounce", MB_OK | MB_ICONINFORMATION);

        switch (pBroadcastHdr->dbch_devicetype)
        {
        case DBT_DEVTYP_DEVICEINTERFACE:
            PDEV_BROADCAST_DEVICEINTERFACE pDevInt = (PDEV_BROADCAST_DEVICEINTERFACE)pBroadcastHdr;

            if (::IsEqualGUID(pDevInt->dbcc_classguid, GUID_DEVINTERFACE_VOLUME))
            {
                PDEV_BROADCAST_VOLUME pVol = (PDEV_BROADCAST_VOLUME)pDevInt;

                char szMsg[80];
                char cDriveLetter = ::GetDriveLetter(pVol->dbcv_unitmask);

                ::wsprintfA(szMsg, "USB disk drive with the drive letter '%c:' has been inserted.", cDriveLetter);
                ::MessageBoxA(NULL, szMsg, "Pounce", MB_OK | MB_ICONINFORMATION);
            }
        }

        return NO_ERROR;
    }

      

In a Windows application, I can get DBT_DEVTYP_VOLUME in dbch_devicetype, however this is not in the Windows Service implementation. Has anyone seen or heard of a solution to this problem without the obvious rewriting as a Windows application?

+2


a source to share


1 answer


Windows 7 supports "running services". If you want to start your service, bypass in a sleep loop, and react whenever something is connected, I think you'd be better off (assuming Windows 7 option) happens with the service start trigger, where the operating system starts the service when USB -the device is connected. (There are other triggers, but you mentioned that.)



The XP2Win7 sample application ( http://code.msdn.microsoft.com/XP2Win7 ) has this functionality enabled. It comes with complete source code. Most of them are in VB and C #, but the startup part is included in (native) C ++.

+2


a source







All Articles