检测机器接入或移除usb设备

要在带有mfc的对话框模式应用程序中检测usb设备的接入或移除,步骤如下:

先包含头文件 #include

(1)需要先xxxDlg.cpp文件中添加消息映射 ON_WM_DEVICECHANGE

BEGIN_MESSAGE_MAP(CVcPhoneAssitDlg, CDialog)
//{{AFX_MSG_MAP(CVcPhoneAssitDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_KEYDOWN()
ON_WM_DEVICECHANGE()// 增加的消息类型
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

同时添加响应函数afx_msg BOOL OnDeviceChange(UINT nEventType, DWORD dwData);   实现如下:

BOOL CxxxxDlg::OnDeviceChange(UINT nEventType,DWORD dwData)
{
	DEV_BROADCAST_DEVICEINTERFACE* pdbd = (DEV_BROADCAST_DEVICEINTERFACE*) dwData;
	
	//匹配guid等
	GUID device_guid;
	memcpy(&device_guid, &pdbd->dbcc_classguid, sizeof(GUID));

	//针对各个事件进行处理.
	switch (nEventType)
	{
		case DBT_DEVICEARRIVAL:
			MessageBox("USB device arrival");
			break;
		case DBT_DEVICEREMOVECOMPLETE:
			MessageBox("USB device removed");
			break;
		default:
			break;
	}
	
	return TRUE;
	
}

(2)注册usb设备类的guid。实现函数为:

void CxxxxDlg::RegisterDevice()
{
	DEV_BROADCAST_DEVICEINTERFACE broadcastInterface = {0};
	// Register to receive notification when a USB device is plugged in.
	broadcastInterface.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
	broadcastInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
	GUID usb_common_class_guid = { 0x25dbce51, 0x6c8f, 0x4a72, 0x8a,0x6d,0xb5,0x4c,0x2b,0x4f,0xc8,0x35 };
	memcpy( &(broadcastInterface.dbcc_classguid),&(usb_common_class_guid), sizeof(struct _GUID));
	HDEVNOTIFY    hDeviceNotify  = RegisterDeviceNotification(m_hWnd,&broadcastInterface, DEVICE_NOTIFY_WINDOW_HANDLE);
}
(3)在对话框类CxxxxDlg的初始化函数 OnInitDialog中调用 RegisterDevice();

BOOL CxxxxDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	RegisterDevice();//register device,


	return TRUE;  // return TRUE  unless you set the focus to a control
}

注意:一定要先调用函数RegisterDevice()注册设备类的guid,否则OnDeviceChange收不到具体的设备事件参数, 而且nEventType 的值一直为0007。

你可能感兴趣的:(移动开发)