SerialEvent.h 2.3 KB

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