MFC 如何检测到USB设备插入拔出


MFC USB设备插入和拔出事件需要使用自定义消息处理,自己添加CODE。


1. 添加消息MAP(也可打开资源视图->类向导->添加消息)

BEGIN_MESSAGE_MAP(CWVKeyAutoWRDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_SIZE()
	ON_BN_CLICKED(IDC_BUTTON_START, &CWVKeyAutoWRDlg::OnBnClickedButtonStart)
	ON_MESSAGE(WM_USER_RUN_COMPLETE, &CWVKeyAutoWRDlg::OnUserRunComplete)
	ON_WM_ACTIVATE()
	ON_WM_DEVICECHANGE() //此消息就是处理设备添加删除
END_MESSAGE_MAP()

2. 消息响应函数声明 *.h文件中

protected:
	afx_msg BOOL OnDeviceChange(UINT nEventType, DWORD dwData);

3. 注册USB设备消息,不注册消息处理函数无法响应, 只有注册了该设备,OnDeviceChange才能获得详细的信息,否则收到的nEventType参数都是0007,dwData无数据。解决方法://DEVICE_NOTIFY_ALL_INTERFACE_CLASSES //关注所有设备事件 m_hDeviceNotify = RegisterDeviceNotification(this->m_hWnd,&Filter,DEVICE_NOTIFY_ALL_INTERFACE_CLASSES);

代码:

BOOL CWVKeyAutoWRDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

        // 注意
	DEV_BROADCAST_DEVICEINTERFACE Filter;
	ZeroMemory(&Filter,sizeof(Filter));
	Filter.dbcc_size = sizeof(Filter);   // size gets set to 29 with 1-byte packing or 32 with 4- or 8-byte packing
	Filter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
	Filter.dbcc_classguid = WceusbshGUID;
	//DEVICE_NOTIFY_ALL_INTERFACE_CLASSES //关注所有设备事件
	m_hDeviceNotify = RegisterDeviceNotification(this->m_hWnd,&Filter,DEVICE_NOTIFY_ALL_INTERFACE_CLASSES);
	if(NULL == m_hDeviceNotify)
		TRACE("RegisterDeviceNotification failed!!");



	return TRUE;  //
}

4.  消息处理函数

BOOL CWVKeyAutoWRDlg::OnDeviceChange(UINT nEventType,DWORD dwData)  
{  
	//DEV_BROADCAST_DEVICEINTERFACE* dbd = (DEV_BROADCAST_DEVICEINTERFACE*) dwData;
	PDEV_BROADCAST_HDR devHdr;
	PDEV_BROADCAST_DEVICEINTERFACE devInterface;
	switch (nEventType)  
	{  
	case DBT_DEVICEREMOVECOMPLETE://移除设备
		break;
	case DBT_DEVICEARRIVAL://添加设备  
		if (m_bAuto_Flash_wvkey)
		{
			devHdr = (PDEV_BROADCAST_HDR)dwData;
			devInterface = (PDEV_BROADCAST_DEVICEINTERFACE)devHdr;
			if (CheckPidVidByGuid(WceusbshGUID))
				OnStartCallFlashWVKey();

		}
		break;  

	default:  
		break;  
	}  

	return TRUE;  
}



注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号