本文介绍了用C ++打开一个COM端口,其端口号大于9的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中使用COM端口.我无法打开大于9的数字的COM端口,例如10.这是用于COM端口检测的功能:

I am using a COM port in C++. I can not open COM ports with a higher number than 9, for example 10. This is function used for COM port detection:

WCHAR port_name[7];
WCHAR num_port[4];

for (i=1; i<256; i++)
{
    bool bSuccess = false;

    wcscpy(port_name,L"COM");
    wcscat(port_name,_itow(i,num_port,10));

    HANDLE hPort;

    //Try to open the port
    hPort = CreateFile(L"COM10", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
    //hPort = CreateFile(port_name, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

    if (hPort == INVALID_HANDLE_VALUE)
    {
        DWORD dwError = GetLastError();

        //Check to see if the error was because some other application had the port open
        if (dwError == ERROR_ACCESS_DENIED)
        {
            bSuccess = TRUE;
            j=j+1;
        }
    }
    else   //The port was opened successfully
    {
        bSuccess = TRUE;
        j=j+1;

        CloseHandle(hPort);   //closing the port
    }

    if (bSuccess)array_ports[j]=i;

}

我不明白为什么例如COM10会将FFFFFFFF扔回HANDLE hPort.

I can not understand why for example COM10, throws FFFFFFFF back to HANDLE hPort.

hPort = CreateFile(L"COM10", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

COM9,COM8,COM7等都可以正常工作,

COM9, COM8, COM7, etc. works fine,

hPort = CreateFile(L"COM9", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

有解决这个问题的方法吗?

It there a solution for this problem?

推荐答案

这是一个错误,解决方法是使用字符串

It is a bug and the resolution is to use the string

\\.\COM10

hPort = CreateFile("\\\\.\\COM10", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

检查文章.

这篇关于用C ++打开一个COM端口,其端口号大于9的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 19:53