串口热插拔的实现

来源:互联网 发布:sql语句 数据类型 编辑:程序博客网 时间:2024/06/10 13:15

      

             根据网上资料实现的串口热插拔,记录下来


            首先手动添加ON_WM_DEVICECHANGE()到

            BEGIN_MESSAGE_MAP(CxxxxxDlg, CDialogEx)

           ON_WM_SYSCOMMAND()

            END_MESSAGE_MAP()

            注意千万不要添加到

             BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
             ON_WM_TIMER()
             END_MESSAGE_MAP()

             在头文件里面添加消息响应函数

             afx_msg BOOL OnDeviceChange(UINT nEventType, DWORD_PTR dwData);

            

             定义消息响应函数

            

BOOL CxxxxxDlg::OnDeviceChange(UINT nEventType, DWORD_PTR dwData){//DEV_BROADCAST_DEVICEINTERFACE* dbd = (DEV_BROADCAST_DEVICEINTERFACE*) dwData;switch (nEventType){ case DBT_DEVICEARRIVAL:{CUIntArray portse, portsu;EnumerateSerialPorts(ports, portse, portsu);unsigned short uicounter;unsigned short uisetcom;CString str;int inseldex = m_ComList.GetCurSel();m_ComList.GetLBText(inseldex, m_strPort);//获取可用串口个数  uicounter = ports.GetSize();m_ComList.ResetContent();//如果个数大于0  if (uicounter > 0){//初始化串口列表框  for (int i = 0; i < uicounter; i++){uisetcom = ports.ElementAt(i);str.Format(_T("COM%d "), uisetcom);m_ComList.AddString(str);}m_ComList.SetCurSel(0);}break;}case DBT_DEVICEREMOVECOMPLETE:{CUIntArray portse, portsu;EnumerateSerialPorts(ports, portse, portsu);unsigned short uicounter;unsigned short uisetcom;CString str;int inseldex = m_ComList.GetCurSel();m_ComList.GetLBText(inseldex, m_strPort);//获取可用串口个数  uicounter = ports.GetSize();m_ComList.ResetContent();//如果个数大于0  if (uicounter > 0){m_cstrComList.RemoveAll();//初始化串口列表框  for (int i = 0; i < uicounter; i++){uisetcom = ports.ElementAt(i);str.Format(_T("COM%d "), uisetcom);m_cstrComList.Add(str);m_ComList.AddString(str);}for (int i = 0; i < m_cstrComList.GetSize(); i++){str += m_cstrComList.GetAt(i);}if (str.Find(m_strPort)){m_strPort += "已被拔出";MessageBox(m_strPort);m_ComList.SetCurSel(0);break;}}else{m_ComList.SetCurSel(0);AfxMessageBox(_T("串口已被拔出"));break;}m_ComList.SetCurSel(0);break;}return TRUE;}return FALSE;}

原创粉丝点击