VC++ 监听USB拔插

目录

添加依赖

注册监听

消息循环

处理事件响应

项目下载


 

主要就是三个步骤
1、注册监听
2、消息循环中接受消息
3、处理usb拔插

添加依赖

#include

注册监听

注册监听比较简单,注册需要响应的guid就行
依赖窗口的handle,如果没有窗口的话就需要创建个简单的消息窗口

bool RegisterDevice()
{
	const GUID GUID_DEVINTERFACE_LIST[] = {
		{ 0xA5DCBF10, 0x6530, 0x11D2, { 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED } },
		{ 0x53f56307, 0xb6bf, 0x11d0, { 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b } },
		{ 0x4D1E55B2, 0xF16F, 0x11CF, { 0x88, 0xCB, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30 } }, /* HID */
		{ 0xad498944, 0x762f, 0x11d0, { 0x8d, 0xcb, 0x00, 0xc0, 0x4f, 0xc3, 0x35, 0x8c } } };

	DEV_BROADCAST_DEVICEINTERFACE NotificationFilter;
	ZeroMemory(&NotificationFilter, sizeof(NotificationFilter));
	NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
	NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;

	NotificationFilter.dbcc_classguid = GUID_DEVINTERFACE_LIST[0];
	HDEVNOTIFY hDevNotify = RegisterDeviceNotification(m_hwnd, &NotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE);
	if (!hDevNotify) {
		return false;
	}
	return true;
}

消息循环

在消息循环中接受WM_DEVICECHANGE消息就可以了
消息循环在不同的框架里面不一样,根据情况处理就行
在mfc中要在message_map中添加响应
在win32中要手动创建消息循环,响应WM_DEVICECHANGE

处理事件响应

通过WPARAM区分拔插
通过LPARAM获取拔插设备的信息

void UsbDeviceChange(WPARAM wParam, LPARAM lParam)
{
	if (DBT_DEVICEREMOVECOMPLETE == wParam)//拔
	{
		PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)lParam;
		if (DBT_DEVTYP_DEVICEINTERFACE == pHdr->dbch_devicetype)
		{
			PDEV_BROADCAST_DEVICEINTERFACE pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr;
			wstring dbccName = pDevInf->dbcc_name;
			cout << "usb remove" <dbch_devicetype)
		{
			PDEV_BROADCAST_DEVICEINTERFACE pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr;
			wstring dbccName = pDevInf->dbcc_name;
			cout << "usb arrival" << dbccName.c_str() << endl;
		}
	}
}

项目下载

https://download.csdn.net/download/lhangtk/10645236

你可能感兴趣的:(c++,c,usb,热拔插)