gpt4 book ai didi

c++ - 如何在 Windows 进程回调中断开连接时获取设备信息(硬件 ID)?

转载 作者:行者123 更新时间:2023-11-28 04:16:08 26 4
gpt4 key购买 nike

使用 Windows 进程回调来处理设备更改,我能够在设备到达时设置一个句柄,这让我可以以一种简单的方式查看它的设备属性,例如硬件 ID,而无需进行任何设备枚举。

但是,在“设备断开连接”时,收到的句柄无效,这似乎是正确的,因为设备不再连接,但我无法查看设备属性。有什么方法可以继续使用 handle 吗?

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?

最佳答案

当设备连接时,将断开连接时需要的信息存储在 map 中,您可以在 map 上使用设备独有的东西作为 key 。

当设备断开连接时,使用您在断开连接事件中获得的 key 在 map 中查找信息,然后删除该条目。

例子:

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

关于c++ - 如何在 Windows 进程回调中断开连接时获取设备信息(硬件 ID)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56585816/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com