USB 设备插拔事件处理

时间:2021-03-10 13:00:18

        Windows 系统下,设备连接至电脑或从电脑移除,系统会广播一条 WM_DEVICECHANGE 消息到所有应用程序,在程序的消息处理函数中可以对事件进行相应。

   1: class CMainDlg : public CDialogImpl<CMainDlg> {

   2: public:

   3:     enum { IDD = IDD_MAINDLG };

   4:     

   5:     BEGIN_MSG_MAP(CMainDlg)

   6:         ......

   7:         MESSAGE_HANDLER(WM_DEVICECHANGE, OnDeviceChange)

   8:     END_MSG_MAP()

   9:  

  10:     LRESULT OnDeviceChange(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) {

  11:         if(wParam == DBT_DEVICEARRIVAL) {

  12:             PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)lParam;

  13:             if(pHdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) {

  14:                 PDEV_BROADCAST_DEVICEINTERFACE pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr;

  15:                 CString dbcc_name = pDevInf->dbcc_name;

  16:                 if(dbcc_name.Find(_T("VID_xxxx&PID_xxxx")) != -1) {

  17:                     MessageBox("特定设备已插入");

  18:                 }

  19:             }

  20:         } else if(wParam == DBT_DEVICEREMOVECOMPLETE) {

  21:             PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)lParam;

  22:             if(pHdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) {

  23:                 PDEV_BROADCAST_DEVICEINTERFACE pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr;

  24:                 CString dbcc_name = pDevInf->dbcc_name;

  25:                 if(dbcc_name.Find(_T("Ven_USBKey&Prod_USBKey")) != -1) {

  26:                     MessageBox("特定设备已拔出");

  27:                 }

  28:             }

  29:         }

  30:         return 0;

  31:     }

  32: }