SerialEvent.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #ifndef SERIALEVENT_H
  2. #define SERIALEVENT_H
  3. #include <QObject>
  4. #include <QAbstractNativeEventFilter>
  5. #include <QDebug>
  6. #if WIN32
  7. #include <windows.h>
  8. #include <dbt.h>
  9. class SerialEvent : public QObject, public QAbstractNativeEventFilter
  10. {
  11. Q_OBJECT
  12. public:
  13. bool nativeEventFilter(const QByteArray &eventType, void *message, qintptr *result)
  14. {
  15. (void)result;
  16. if(eventType == "windows_generic_MSG" || eventType == "windows_dispatcher_MSG")
  17. {
  18. MSG* msg = reinterpret_cast<MSG*>(message);
  19. int msgType = msg->message;
  20. if(msgType == WM_DEVICECHANGE)
  21. {
  22. PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)msg->lParam;
  23. switch (msg->wParam)
  24. {
  25. case DBT_DEVICEARRIVAL:
  26. // qDebug() << "DBT_DEVICEARRIVAL:" << lpdb->dbch_devicetype;
  27. if(lpdb->dbch_devicetype == DBT_DEVTYP_PORT)
  28. {
  29. PDEV_BROADCAST_PORT lpdbv = (PDEV_BROADCAST_PORT)lpdb;
  30. QString portName = QString::fromWCharArray(lpdbv->dbcp_name);
  31. qDebug() << "device arrival:" << portName;
  32. emit comDevArriaval(portName);
  33. }
  34. break;
  35. case DBT_DEVICEREMOVECOMPLETE:
  36. // qDebug() << "DBT_DEVICEREMOVECOMPLETE:" << lpdb->dbch_devicetype;
  37. if(lpdb->dbch_devicetype == DBT_DEVTYP_PORT)
  38. {
  39. PDEV_BROADCAST_PORT lpdbv = (PDEV_BROADCAST_PORT)lpdb;
  40. QString portName = QString::fromWCharArray(lpdbv->dbcp_name);
  41. qDebug() << "device remove complete:" << portName;
  42. emit comDevRemoveComplete(portName);
  43. }
  44. break;
  45. case DBT_DEVNODES_CHANGED:
  46. break;
  47. default:
  48. break;
  49. }
  50. }
  51. }
  52. return false;
  53. }
  54. signals:
  55. // 串口插入了
  56. void comDevArriaval(QString devName);
  57. //串口拔掉了
  58. void comDevRemoveComplete(QString devName);
  59. };
  60. #endif
  61. #endif // SERIALEVENT_H