CWnd::OnDeviceChange

由於需要做即時偵測 usb 的插拔動作,所以最近用了onDeviceChange這個功能...但,一直無法進入這個副程式。上網搜尋了一下。發現需要三個步驟才行。

Step 1.在定義 class 成員中加入
protected:
afx_msg BOOL OnDeviceChange( UINT nEventType, DWORD dwData );

Step 2.在 XXX.cpp 中加入BOOL OnDeviceChange(UINT, DWORD);
BOOL CXXXXX::OnDeviceChange( UINT nEventType, DWORD dwData )
{
switch(nEventType)
{
// A device has been inserted and is now available.
case DBT_DEVICEARRIVAL:
// Check to see if newly connected device has VID and PID
// matching HID_Blinky's VID and PID
if (GetNumHidDevices(C2CS_VID,C2CS_PID))
{
// Update Device Status text
m_DeviceStatus = "Connected, Idle";
UpdateWindow = TRUE;
}
break;

// A device has been removed from USB.
case DBT_DEVICEREMOVECOMPLETE:
// Check that the HID_Blinky device was the removed device
if (!GetNumHidDevices(C2CS_VID,C2CS_PID))
{
// Call routine that will terminate communication and
// destroy a receive thread, if one has been created
m_DeviceStatus = "Disconnected";
UpdateWindow = TRUE;
}
break;

default:
break;
}
return TRUE;
}

Step 3.加入
BEGIN_MESSAGE_MAP(CXXXXXX, CDialog)
//{{AFX_MSG_MAP(CTest031Dlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_DEVICECHANGE() // add this one
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

下列是 OnDeviceChange 的 Parameters 定義
The nEvent parameter can be one of these values:
DBT_DEVICEARRIVAL A device has been inserted and is now available.
DBT_DEVICEQUERYREMOVE Permission to remove a device is requested. Any application can deny this request and cancel the removal.
DBT_DEVICEQUERYREMOVEFAILED Request to remove a device has been canceled.
DBT_DEVICEREMOVEPENDING Device is about to be removed. Cannot be denied.
DBT_DEVICEREMOVECOMPLETE Device has been removed.
DBT_DEVICETYPESPECIFIC Device-specific event.
DBT_CONFIGCHANGED Current configuration has changed.
DBT_DEVNODES_CHANGED Device node has changed.


補充:20100126,
需要向 windows 註冊 usb device。所以需要增加下列

// dialog box will be notified whenever a USB device is attached or removed from the USB
void TestDlg::RegisterNotification()
{
// Register device notification
DEV_BROADCAST_DEVICEINTERFACE devIF = {0};
GUID hidGuid;

GetHidGuid(&hidGuid);

devIF.dbcc_size = sizeof(devIF);
devIF.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
devIF.dbcc_classguid = hidGuid;

m_hNotifyDevNode = RegisterDeviceNotification(GetSafeHwnd(),
&devIF, DEVICE_NOTIFY_WINDOW_HANDLE);
}

並在 OnInitDialog() 中加入 RegisterNotification()
BOOL TestDlg::OnInitDialog()
{
.........................
RegisterNotification();

...........
}

留言

  1. include "Dbt.h" 還是認不得 DBT_DEVTYP_DEVICEINTERFACE, 甚至 RegisterDeviceNodification() 都認不得。請問您用的 compile 環境是甚麼? 我是 Windows XP, Visual Studio 6.0

    回覆刪除

張貼留言

這個網誌中的熱門文章

NMEA標準格式 -- GPS

網路 Transformer 的用途

cut,sed,awk 字串處理