我对窗口编程很新。 我在QT5中实现了一个托盘,当特定设备与PC连接/断开时,该托盘显示一条消息。 我创建了仅限消息的窗口,用于接收USB设备的断开/连接。一切都好,直到这里,我收到的消息是每次插拔设备的电缆/从电脑上拔掉两次。(不要认为Windows 10在发送它时是如此慷慨2次)
我的问题:为什么会发生这种情况,不应该只发生一次吗?
**已经回答了这个问题,因为该设备显示为HID和USB,其PID / VID与此处编程的相同。
以下是代码:
GUID InterfaceClassGuid = { 0x745a17a0, 0x74d3, 0x11d0, { 0xb6, 0xfe, 0x00, 0xa0, 0xc9, 0x0f, 0x57, 0xda } };
// Registration method
void usbMessage::RegisterNotification()
{
// Set GUID filter data
if (usbCNCMsg != nullptr) {
_pDevIF = (DEV_BROADCAST_DEVICEINTERFACE *)malloc(sizeof(DEV_BROADCAST_DEVICEINTERFACE));
memset(_pDevIF, 0, sizeof(DEV_BROADCAST_DEVICEINTERFACE));
_pDevIF->dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
_pDevIF->dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
_pDevIF->dbcc_classguid = InterfaceClassGuid;
// Register for notifications
_hNotifyDev = RegisterDeviceNotification(this->GetSafeHwnd(), _pDevIF, DEVICE_NOTIFY_ALL_INTERFACE_CLASSES);
if (!_hNotifyDev) {
AfxMessageBox(CString("Can't register device notification: ")
+ _com_error(GetLastError()).ErrorMessage(), MB_ICONEXCLAMATION);
}
} else {
qDebug() << "There was no connection msg Obj passed. MFC msg queue not enabled.";
}
}
bool usbMessage::matchVidPid(QString dbcc_name)
{
QString devicePid;
QString deviceVid;
int indx = dbcc_name.indexOf("#");
int indx2 = dbcc_name.indexOf("&");
deviceVid = dbcc_name.mid(indx + 1, PID_VID_LENGTH);
devicePid = dbcc_name.mid(indx2 + 1, PID_VID_LENGTH);
if (deviceVid == VID_STRNG &&
devicePid == PID_STRNG) {
return true;
}
return false;
}
LRESULT usbMessage::OnMyDeviceChange(WPARAM wParam, LPARAM lParam)
{
PDEV_BROADCAST_DEVICEINTERFACE pDevInf;
if (DBT_DEVICEARRIVAL == wParam || DBT_DEVICEREMOVECOMPLETE == wParam) {
PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)lParam;
switch (pHdr->dbch_devicetype) {
case DBT_DEVTYP_DEVICEINTERFACE:
pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr;
if (matchVidPid(QString::fromWCharArray(pDevInf->dbcc_name))) {
if (DBT_DEVICEARRIVAL == wParam) {
this->usbCNCMsg->sendMessageConnected(trayMsgHelper::getDeviceConnectedMsg());
}
if (DBT_DEVICEREMOVECOMPLETE == wParam) {
this->usbCNCMsg->sendMessageDisconnected(trayMsgHelper::getDeviceDisconnectedMsg());
}
}
break;
}
}
return 0;
}
谢谢!