2

我正在尝试检测插入到 Windows 服务中的 USB 磁盘驱动器,我已将其作为普通 Windows 应用程序执行。问题是以下代码不适用于卷。

注册设备通知:

    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);

ServiceControlHandlerEx 函数的代码:

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;
    }

在 Windows 应用程序中,我能够在 dbch_devicetype 中获得 DBT_DEVTYP_VOLUME,但是这在 Windows 服务实现中不存在。有没有人看到或听说过这个问题的解决方案,没有明显的,重写为 Windows 应用程序?

4

1 回答 1

2

Windows 7 supports "trigger started services". If you want to start your service, go around in a sleeping loop, and react whenever something is plugged in, I think you would be better off (assuming Windows 7 is an option) going with a trigger started service where the OS starts the service when a USB device is plugged in. (There are other triggers but you mentioned this one.)

The sample application XP2Win7 (http://code.msdn.microsoft.com/XP2Win7) includes this functionality. It comes with full source code. Most is in VB and C# but the trigger started services part is in (native) C++.

于 2010-04-14T15:58:46.720 回答