Windows系统 获取串口的方法C++

一、Windows下开发,怎么获取当前串口呢

  • 使用Qt的童鞋都知道,Qt提供了丰富的接口,包括串口。但是对于串口的支持,是从Qt5开始的,对于Qt4来说,虽然也可以使用Qt的库,但是并不是很方便。不是Qt环境就更不用说了。本文提供了一个封装好的方法,可以方便的获取当前可用的串口。

二、代码实现

#include "string.h"
#include "stdio.h"
#include <vector>  
#include <string>  
#include <atlbase.h>
 
// 字符串转换
char* wideCharToMultiByte(wchar_t* pWCStrKey)
{
    //第一次调用确认转换后单字节字符串的长度,用于开辟空间
    int pSize = WideCharToMultiByte(CP_OEMCP, 0, pWCStrKey, wcslen(pWCStrKey), NULL, 0, NULL, NULL);
    char* pCStrKey = new char[pSize + 1];
    //第二次调用将双字节字符串转换成单字节字符串
    WideCharToMultiByte(CP_OEMCP, 0, pWCStrKey, wcslen(pWCStrKey), pCStrKey, pSize, NULL, NULL);
    pCStrKey[pSize] = '\0';
    return pCStrKey;

    //如果想要转换成string,直接赋值即可
    //string pKey = pCStrKey;
}

std::vector<std::string> getComPort()
{
    HKEY hKey;
    wchar_t portName[256], w_commName[256];
    std::vector<std::string> comName;
    //打开串口注册表对应的键值  
    if (ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Hardware\\DeviceMap\\SerialComm"), NULL, KEY_READ, &hKey))
    {
        int i = 0;
        int mm = 0;
        DWORD  dwLong, dwSize;
        while (TRUE)
        {
            dwLong = dwSize = sizeof(portName);
            //枚举串口
            if (ERROR_NO_MORE_ITEMS == ::RegEnumValue(hKey, i, portName, &dwLong, NULL, NULL, (PUCHAR)w_commName, &dwSize))
            {
                break;
            }
            char* commName = wideCharToMultiByte(w_commName);
            comName.push_back(commName);
            delete[] commName;
            i++;
        }
        //关闭注册表
        RegCloseKey(hKey);
    }
     
    //返回串口号
    return comName;
}

 

// 使用示例
QString getAvailableSerialPortTest()
{
    std::vector<int> vecPortList;
    std::vector<std::string> vecList =  getComPort(); 
    for (int i = 0;i<vecList.size();i++)
    {
        std::string strCom = vecList[i];
        std::string strPort = strCom.substr(3,1); 
        int nPort = stoi(strPort,0,10);

        vecPortList.push_back(nPort); 
    }

    QString strExist;
    for (int i=0;i<vecPortList.size();i++)
    {
        strExist+=QString::number(vecPortList[i]) + "   ";
    }
   
  return strExist; 
}

三、总结

  • 以上程序,可以快速方便的获取可用端口。但是,只限于windows系统。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SetWindowsHookEx函数是Windows API中的一个函数,可以用于设置系统钩子,用于拦截系统事件。如果想要在C++中获取串口数据,可以使用该函数来设置钩子,拦截串口数据的传输事件。 以下是一个简单的示例代码: ```c++ #include <iostream> #include <Windows.h> HHOOK hHook; HWND hWnd; LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode >= 0) { KBDLLHOOKSTRUCT* pKeyboard = (KBDLLHOOKSTRUCT*)lParam; if (pKeyboard->vkCode == VK_RETURN) { // 读取串口数据 char buffer[1024]; DWORD bytesRead; ReadFile(hComm, buffer, sizeof(buffer), &bytesRead, NULL); std::cout << "Received data: " << buffer << std::endl; } } return CallNextHookEx(hHook, nCode, wParam, lParam); } int main() { HANDLE hComm; char portName[] = "COM1"; DCB dcbSerialParams = { 0 }; COMMTIMEOUTS timeouts = { 0 }; // 打开串口 hComm = CreateFile(portName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (hComm == INVALID_HANDLE_VALUE) { std::cout << "Failed to open port." << std::endl; return 1; } // 设置串口参数 dcbSerialParams.DCBlength = sizeof(dcbSerialParams); if (!GetCommState(hComm, &dcbSerialParams)) { std::cout << "Failed to get current serial parameters." << std::endl; return 1; } dcbSerialParams.BaudRate = CBR_9600; dcbSerialParams.ByteSize = 8; dcbSerialParams.StopBits = ONESTOPBIT; dcbSerialParams.Parity = NOPARITY; if (!SetCommState(hComm, &dcbSerialParams)) { std::cout << "Failed to set serial parameters." << std::endl; return 1; } // 设置串口超时时间 timeouts.ReadIntervalTimeout = 50; timeouts.ReadTotalTimeoutConstant = 50; timeouts.ReadTotalTimeoutMultiplier = 10; timeouts.WriteTotalTimeoutConstant = 50; timeouts.WriteTotalTimeoutMultiplier = 10; if (!SetCommTimeouts(hComm, &timeouts)) { std::cout << "Failed to set serial timeouts." << std::endl; return 1; } // 设置系统钩子 hWnd = GetConsoleWindow(); hHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, NULL, 0); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } // 关闭钩子 UnhookWindowsHookEx(hHook); // 关闭串口 CloseHandle(hComm); return 0; } ``` 该示例代码在主函数中通过SetWindowsHookEx函数设置了一个全局的键盘钩子,用于拦截按键事件。在钩子函数KeyboardProc中,当捕获到回车键按下事件时,通过ReadFile函数读取串口数据,并将数据打印到控制台上。最后在主函数中通过GetMessage函数循环等待消息,直到程序退出。需要注意的是,由于SetWindowsHookEx函数设置的是全局钩子,因此该程序会拦截所有进程中的键盘事件。 这种方法虽然可以拦截串口传输事件,但是可能会影响系统性能,因此需要谨慎使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值