USB 设备插拔事件处理

        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: }

上一篇:C#常用功能函数小结(.NET 4.5)


下一篇:360自带--JS开发工具箱