SerialPort类打开超过9串口问题

来源:互联网 发布:node书推荐 编辑:程序博客网 时间:2024/06/05 09:21
高手进来看看,SerialPort是不是有问题,出现不能打开超过9的串口,比如COM10就不行
进行跟踪调试发现在SerialPort的InitPort方法中,的CreateFile行返回的错误代码是INVALID_HANDLE_VALUE,我用MSCOMM和超级终端都能打开COM10,这是为什么?

CreateFile( 
"\\\\.\\COM10 ",//对应的就是\\.\COM10 
GENERIC_READ | GENERIC_WRITE, 
0, 
NULL, 
OPEN_EXISTING, 
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, //重叠I/O 
NULL 

);


在做一个串口通讯,遇到了这个问题,com1到com9正常打开,com10以上就不行了,用getlasterror查看,错误位找不到指定文件,后查看MSDN,解释如下:

Windows NT: You can use paths longer than MAX_PATH characters by calling the wide (W) version of CreateFile and prepending "\\?\" to the path. The "\\?\" tells the function to turn off path parsing. This lets you use paths that are nearly 32,000 Unicode characters long. However, each component in the path cannot be more than MAX_PATH characters long. You must use fully-qualified paths with this technique. This also works with UNC names. The "\\?\" is ignored as part of the path. For example, "\\?\C:\myworld\private" is seen as "C:\myworld\private", and "\\?\UNC\tom_1\hotstuff\coolapps" is seen as "\\tom_1\hotstuff\coolapps". 

当路径长度大于MAX_PATH 后,应加上"\\?\",个人猜想,可能打开串口的话只能支持com1到com9,大于4个字符就不行了,故com10以上应添加"\\?\",即

CreateFile("\\\\?\\COM10", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);

这样就能成功打开。以上方法所有com1~9也是可以的,所以建议就用这种方法吧。

后在网上看到说加"\\.\",试了一下也可以,和"\\?\"一样,我现在就在想“?”到底是什么意思,是不是换成其他符号也可以呢,后来试了,只有换成“."可以,关于这个问题还请高手解答。


1 0
原创粉丝点击