MFC之设备插入拔出检测

0

主要有以下步骤:

1. 添加消息映射

BEGIN_MESSAGE_MAP(demoDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_TIMER()
	ON_WM_DEVICECHANGE()
END_MESSAGE_MAP()

2.  声明消息处理函数

afx_msg BOOL OnDeviceChange(UINT nEventType, DWORD dwData);

3. 实现消息处理函数

BOOL demoDlg::OnDeviceChange(UINT nEventType, DWORD dwData)
{
	DEV_BROADCAST_DEVICEINTERFACE* dbd = (DEV_BROADCAST_DEVICEINTERFACE*)dwData;
	//这里进行信息匹配,比如 GUID 等信息

	//针对各个事件进行处理.
	switch (nEventType)
	{
	case DBT_DEVICEARRIVAL:		//设备插入
                ... ...
		break;
	case DBT_DEVICEREMOVECOMPLETE:	//设备拔出
                ... ...
		break;
	default:
		break;
	}
	return TRUE;
}

4. 注册设备插拔通知事件

DEV_BROADCAST_DEVICEINTERFACE DevInt;
memset(&DevInt, 0, sizeof(DEV_BROADCAST_DEVICEINTERFACE));
DevInt.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
DevInt.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
DevInt.dbcc_classguid = { 0x4d1e55b2, 0xf16f, 0x11cf, { 0x88, 0xcb, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30 } }; //HID_CLASS
if (!RegisterDeviceNotification(this->GetSafeHwnd(), &DevInt, DEVICE_NOTIFY_WINDOW_HANDLE))
	return FALSE;

搞定!

Leave A Reply