1. 设备状态改变设别注册:
当设备插入或拔下时,windows应用程序可以感知并作出相关动作。要实现这个功能,需要在应用程序中,先申请注册接收该设备类(包括HID类)状态改变时产生的通知。
注册设备状态改变通知要使用函数RegisterDeviceNotification(),HID设备类注册的具体代码如下:
里面有很多宏及结构定义,使用前需要添加头文件 include "dbt.h"
void CPCRProjectDlg::RegisterForDeviceNotifications()
{
// Request to receive messages when a device is attached or removed.
// Also see WM_DEVICECHANGE in BEGIN_MESSAGE_MAP(CPCRProjectDlg, CDialog).
DEV_BROADCAST_DEVICEINTERFACE DevBroadcastDeviceInterface;
HDEVNOTIFY DeviceNotificationHandle;
DevBroadcastDeviceInterface.dbcc_size = sizeof(DevBroadcastDeviceInterface);
DevBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
DevBroadcastDeviceInterface.dbcc_classguid = HidGuid;
DeviceNotificationHandle =
RegisterDeviceNotification(m_hWnd, &DevBroadcastDeviceInterface, DEVICE_NOTIFY_WINDOW_HANDLE);
}
注意:该函数使用的位置,要在HID设备找到后的位置使用,如在PCR项目中,要在FindHID()函数内,如下位置使用:
switch(Attributes.VendorID)
{
case GRA_VID:
{
if (Attributes.ProductID == GRA_PID) // 找到 GRA这个HID设备
{
//Both the Vendor ID and Product ID match.
//Register to receive device notifications.
RegisterForDeviceNotifications();
....
break:
}
case TEM_VID:
{
if (Attributes.ProductID == TEM_PID) // 找到TEM这个HID设备
{
//Register to receive device notifications.
RegisterForDeviceNotifications();
....
break:
}
default: break;
}
如果在找到HID之前使用,比如在OnInitial()函数中使用,在后面的对应消息处理函数中,其参数就会错误。
2. 设备热插拔对应消息及处理函数:
设备状态变化通知接收注册成功后,当设备的状态发生变化(插、拔)时,事件的接收者(在注册时制定)就会收到一个WM_DEVICECHANGE的消息。
接下来在程序中添加WM_DEVICECHANGE消息对应的处理函数:
2.1 在对应类的.h头文件中添加处理函数定义:
// CPCRProjectDlg dialog
class CPCRProjectDlg : public CDialogEx
{
// Construction
public:
CPCRProjectDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
enum { IDD = IDD_PCRPROJECT_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual void OnOK();
virtual void OnCancel();
// Implementation
protected:
HICON m_hIcon;
LRESULT Main_OnDeviceChange(WPARAM wParam, LPARAM lParam);
......
}
2.2 在类的对应消息列表添加消息和对应函数声明
BEGIN_MESSAGE_MAP(CPCRProjectDlg, CDialogEx)
......
ON_MESSAGE(WM_DEVICECHANGE, Main_OnDeviceChange)
END_MESSAGE_MAP()
2.3 添加消息处理函数Main_OnDeviceChange()的具体实现:
LRESULT CPCRProjectDlg::Main_OnDeviceChange(WPARAM wParam, LPARAM lParam)
{
//DisplayData("Device change detected.");
PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)lParam;
// if(FindTheHID()) m_TrimDlg.ResetTrim();
// FindTheHID();
switch(wParam)
{
// Find out if a device has been attached or removed.
// If yes, see if the name matches the device path name of the device we want to access.
case DBT_DEVICEARRIVAL: // HID pull in
FindTheHID();
return TRUE;
case DBT_DEVICEREMOVECOMPLETE: // HID pull out
FindTheHID();
return TRUE;
default:
return TRUE;
}
return TRUE;
}