您的位置:首页 > 运维架构

QTC++监控USB插拔

2015-08-26 11:26 579 查看
#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


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: