(转)VC得到可用的串口列表

//枚举串口
//参数:bEnablePort,哪个串口有效,bEnablePort[0]表示COM1,bEnablePort[n-1]表示COMn
//返回值:有效的串口个数
int EnumAllComPort(bool* bEnablePort)
{
    int nCommSum = 0;//串口个数

    HANDLE hCom;
    CString str;

    for(int i=1;i<=256;i++)
    {
        str.Format(_T("COM%d"),i);
        hCom = CreateFile(str, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
        if (hCom == INVALID_HANDLE_VALUE)
        {
            bEnablePort[i-1] = false;
            continue;
        }
        else
        {
            bEnablePort[i-1] = true;
        }
        CloseHandle(hCom);
        nCommSum++;
    }

    return nCommSum;
} 
 
 
原文地址:http://blog.csdn.net/hanjiangying/article/details/5490854
posted @ 2017-06-13 15:40  lydit  阅读(845)  评论(0编辑  收藏  举报