c++ - 如何在 Windows 进程回调中获取断开连接的设备信息(硬件 ID)?
问题描述
使用 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";
}
}
}
推荐阅读
- r - 在列表的 lapply 函数中获取数据框名称(ggplot2)
- ios - 有没有办法让拖尾的滑动操作像 macOS 11.0 一样具有圆角?
- kotlin - Kotlin 中“For 循环”中 Thread.Sleep() 的替代方案?
- javascript - 每次访问与模式匹配的 url 时,在 chrome 扩展的后台脚本中添加一个监听器到 webNavigation
- graphql - 使用 Apollo GraphQl 的待办事项列表乐观订阅更新
- r - 频率值作为颜色变量的热图
- r - 在 R 中对数据集进行多重相关的循环
- python - Pandas.plot 不会绘制 Series 对象的所有行
- github-pages - Hugo 站点托管在 GitHub Pages 中。主页显示正常,但博客转到 404
- android - Android Webview:页面加载时显示图像