[英]How to get device info (hardware IDs) on disconnect in Windows process callback?
使用Windows进程回调进行设备更改,我能够在设备到达时设置一个句柄,让我以一种简单的方式查看它的设备属性(如硬件ID),而无需进行任何设备枚举。
但是,在“设备断开连接”上,收到的句柄无效,这似乎是正确的,因为该设备不再连接,但是我无法查看设备属性。 有没有办法可以使用手柄?
DEV_BROADCAST_HDR* devHDR = reinterpret_cast<DEV_BROADCAST_HDR*>(lParam);
if (devHDR->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)
{
DEV_BROADCAST_DEVICEINTERFACE* devInterface = reinterpret_cast<DEV_BROADCAST_DEVICEINTERFACE*>(lParam);
DeviceHandle = CreateFile(devInterface->dbcc_name, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
if(DeviceHandle == != INVALID_HANDLE_VALUE){
// arrive gets here
} else {
// disconnect gets here
}
}
基本上,由于无法获得有效的断开连接句柄,因此无法从DEV_BROADCAST_DEVICEINTERFACE结构获得硬件ID和其他数据。 有没有其他方法可以在断开连接时获取设备硬件ID?
当设备连接时,将断开连接所需的信息存储在地图中,在该地图中,您使用该设备的唯一信息作为键。
当设备断开连接时,使用在断开连接事件中获得的密钥在地图中查找信息,然后删除该条目。
例:
using String = std::basic_string<TCHAR>;
// a struct with all the properties you'd like to use on disconnect
struct device_info {
CHANGER_PRODUCT_DATA cpd; // just an example
String something;
};
int main() {
// a map where the device_name is the key and device_info the value
std::unordered_map<String, device_info> devices;
{ // on connect, create a device_info struct and fill it with the info you need on
// disconnect
DEV_BROADCAST_DEVICEINTERFACE* devInterface =
reinterpret_cast<DEV_BROADCAST_DEVICEINTERFACE*>(lParam);
String new_dev_name { devInterface->dbcc_name };
device_info di{}; // store what you need from the opened device here
// and put it in the map
devices.emplace(new_dev_name, di);
}
{ // on disconnect, find the entry in the map using the disconnected device_name
DEV_BROADCAST_DEVICEINTERFACE* devInterface =
reinterpret_cast<DEV_BROADCAST_DEVICEINTERFACE*>(lParam);
String disc_dev_name{ devInterface->dbcc_name };
auto fit = devices.find(disc_dev_name);
if (fit != devices.end()) {
// we found the device, extract it
device_info disc_di = fit->second;
// and erase it from the map
devices.erase(fit);
std::wcout << "\"" << disc_di.something << "\" disconnected\n";
}
}
}
您的方法不正确。
您必须首先检查wParam并测试== DBT_DEVICEARRIVAL和== DBT_DEVICEREMOVECOMPLETE
在DBT_DEVICEREMOVECOMPLETE测试中,将填充lParam以获取DEV_BROADCAST_HANDLE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.