QTC++监控USB插拔
#if defined(Q_OS_WIN) #include <qt_windows.h> #include <QtCore/qglobal.h> #include <dbt.h> #endif QByteArray *MainWindow::receivedData=new QByteArray();//接收到数据 ThreadComPort *MainWindow::threadInitComPort=0; #if defined(Q_OS_WIN) static const GUID GUID_DEVINTERFACE_USBSTOR = { 0xA5DCBF10L, 0x6530, 0x11D2, { 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED } }; static const GUID InterfaceClassGuid = GUID_DEVINTERFACE_USBSTOR; static bool isDoingSearch=false; static void SerachComPort(){ if(isDoingSearch==false){ isDoingSearch=true; bool hasDevice=false; QList<QSerialPortInfo> list= QSerialPortInfo::availablePorts(); for(int i=0;i<list.count();i++){ if(list[i].description().contains("USB CDC",Qt::CaseInsensitive)){ qDebug()<<"设备已经插入,端口:"<<list[i].portName(); Globals::PortName=list[i].portName(); hasDevice=true; } } if(!hasDevice){ qDebug()<<"请插入设备"; Globals::PortName="NoDevice"; AddControl(new NoDevice()); Globals::parent->InitComPort(); } isDoingSearch=false; } } LRESULT CALLBACK dw_internal_proc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == WM_DEVICECHANGE) { switch (wParam) { case DBT_DEVNODES_CHANGED: qDebug()<<"设备插拔啦."; Globals::parent->CloseComPort(); SerachComPort(); break; } } // qDebug()<<"HWND:"<<hwnd; return DefWindowProc(hwnd, message, wParam, lParam); } static inline HWND WndProc(const void* userData) { QString className="UsbMonitor"; HINSTANCE hi = qWinAppInst(); WNDCLASS wc; wc.style = 0; wc.lpfnWndProc = dw_internal_proc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hi; wc.hIcon = 0; wc.hCursor = 0; wc.hbrBackground = 0; wc.lpszMenuName = NULL; wc.lpszClassName = reinterpret_cast<const wchar_t *>(className.utf16()); RegisterClass(&wc); HWND hwnd = CreateWindow(wc.lpszClassName, // classname wc.lpszClassName, // window name 0, // style 0, 0, 0, 0, // geometry 0, // parent 0, // menu handle hi, // application 0); // windows creation data. if (hwnd) { DEV_BROADCAST_DEVICEINTERFACE NotificationFilter ; ZeroMemory(&NotificationFilter, sizeof(NotificationFilter)) ; NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE); NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; NotificationFilter.dbcc_classguid = InterfaceClassGuid; RegisterDeviceNotification(hwnd, &NotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE); } return hwnd; } #endif