我正在尝试检测正在Windows服务中插入的USB磁盘驱动器,我已将其作为普通的Windows应用程序完成。问题是以下代码不适用于卷。
注册设备通知:
DEV_BROADCAST_DEVICEINTERFACE notificationFilter;
HDEVNOTIFY hDeviceNotify = NULL;
::ZeroMemory(¬ificationFilter, 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, ¬ificationFilter, 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应用程序?
答案 0 :(得分:2)
Windows 7支持“触发启动服务”。如果你想开始你的服务,在一个睡眠循环中四处走动,并在插入某些东西时作出反应,我认为你会更好(假设Windows 7是一个选项)与触发启动服务一起运行OS启动服务当插入USB设备时。(还有其他触发器,但你提到了这个。)
示例应用程序XP2Win7(http://code.msdn.microsoft.com/XP2Win7)包含此功能。它附带完整的源代码。大多数是VB和C#,但触发器启动服务部分是(本机)C ++。