首页 > 代码库 > MFC检测串口插拔

MFC检测串口插拔

以对话框工程为例


头文件中

afx_msg BOOL OnDeviceChange(UINT nEventType, DWORD dwData);

cpp中

ON_WM_DEVICECHANGE() 

然后实现函数

BOOL CXXDlg::OnDeviceChange(UINT nEventType,DWORD dwData)
{
	//0x4d36e978L, 0xe325, 0x11ce, 0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18
	//DEV_BROADCAST_DEVICEINTERFACE* dbd = (DEV_BROADCAST_DEVICEINTERFACE*) dwData;

	DEV_BROADCAST_HDR* dhr = (DEV_BROADCAST_HDR *)dwData;
	TRACE("--nEventType--:%d\n", nEventType);
	switch (nEventType)
	{
	case DBT_DEVICEREMOVECOMPLETE://移除设备
		TRACE("--DEVICE REMOVE--\n");
#if 1
		if(dhr->dbch_devicetype == DBT_DEVTYP_PORT) 
		{ 
			PDEV_BROADCAST_PORT lpdbv = (PDEV_BROADCAST_PORT)dhr; 
			int len = strlen(lpdbv->dbcp_name);
			CString name(lpdbv->dbcp_name);//COM8
			int port = 0;
			sscanf(name.GetBuffer(0), "COM%d", &port);
		} 
#endif
		TRACE("--DEVICE REMOVE--end\n");
		break;
	case DBT_DEVICEARRIVAL://添加设备
		TRACE("--DEVICE ARRIVAL--\n");
#if 1		
		if(dhr->dbch_devicetype == DBT_DEVTYP_PORT) 
		{ 
			PDEV_BROADCAST_PORT lpdbv = (PDEV_BROADCAST_PORT)dhr; 
			int len = strlen(lpdbv->dbcp_name);
			CString name(lpdbv->dbcp_name);//COM8
			int port = 0;
			sscanf(name.GetBuffer(0), "COM%d", &port);
		} 
#endif
		break;
	default:
		break;
	}

	return TRUE;

}