-
创建一个基于对话框的应用,并加入以下控件
-
按ALT+W键,然后为ComboBox控件关联变量
-
准备EnumSerial.cpp和EnumSerial.h文件并加入到工程
文件下载地址:
链接:https://pan.baidu.com/s/1lwrkSH90fteFFD3CAnXeHw
提取码:ih78
-
在工程配置中加入setupapi.lib库
-
在测试对话框CPP中加入头文件
#include "EnumSerial.h"
-
实现方法 void paserComPort(CString &str,CString &port)
void CCom_testDlg:: paserComPort(CString &str,CString &port) { int posBeg = str.Find("("); int posEnd = str.Find(")"); port = str.Mid(posBeg+1,posEnd-posBeg-1);//获取串口的名称COM2 }
-
实现方法 bool CCom_testDlg:: UpgradeDeviceSerialCom(CString &port)
bool CCom_testDlg:: UpgradeDeviceSerialCom(CString &port) { CArray<SSerInfo, SSerInfo&> asi; // Populate the list of serial ports. EnumSerialPorts(asi, TRUE);//FALSE遍历所有的串口,TRUE只是枚举可以打开的串口 //EnumSerialPorts(asi, TRUE); bool is_close_com = false; m_ctrl_com.ResetContent(); int size = asi.GetSize(); for (int ii = 0; ii<size; ii++) { //显示读取串口的全称 m_ctrl_com.InsertString(ii,asi[ii].strFriendlyName); } if(size>0) { m_ctrl_com.SetCurSel(0); for(int i=0;i<size;i++) { if(port.Compare(asi[i].strFriendlyName)==0) is_close_com = true; } } else { is_close_com = true; } return is_close_com; }
-
在OnInitDialog中调用UpgradeDeviceSerialCom()方法
-
插上串口设备编译运行
-
实现热插拔功能
在BEGIN_MESSAGE_MAP和END_MESSAGE_MAP宏之间加入ON_WM_DEVICECHANGE()
加入afx_msg BOOL OnDeviceChange(UINT nEventType, DWORD dwData)声明
OnDeviceChange()方法实现
BOOL CCom_testDlg::OnDeviceChange(UINT nEventType,DWORD dwData)
{
DEV_BROADCAST_DEVICEINTERFACE* dbd = (DEV_BROADCAST_DEVICEINTERFACE*) dwData;
CString m_port_name="";
switch (nEventType)
{
case DBT_DEVICEREMOVECOMPLETE://移除设备
{
int cur_index = m_ctrl_com.GetCurSel();
m_ctrl_com.GetLBText(cur_index,m_port_name);
}
case DBT_DEVICEARRIVAL://添加设备
{
if(DBT_DEVTYP_PORT == dbd->dbcc_devicetype) //串口设备
{
if(UpgradeDeviceSerialCom(m_port_name))//刷新组合框的内容
{
MessageBox("选中的设备被拔除");
}
}
}
break;
default:
break;
}
return TRUE;
}
在对话框CPP文件中加入头文件#include <Dbt.h>,并在stdafx.h文件中定义宏
#define WINVER 0x0500
编译运行
Demo下载地址:https://download.csdn.net/download/mygod2008ok/12249862