在VS2005上用CreateFile打开串口,代码如下:
其中Port是LPCTSTR类型。
如果打开串口1,就传给Port的值为:“COM1”。
因项目需要,需要打开很多串口,发现以上函数到COM10以后就不能用了,始终不能打开串口。即调用CreateFile后,返回的m_hComm为INVALID_HANDLE_VALUE。
在优快云上查看了一下,原文如下:
CreateFile(
"////.//COM10",
// address of name of the communications device
fdwAccess, // access
(read-write) mode
0,
// share mode
NULL, // address of
security descriptor
OPEN_EXISTING, // how to create
0,
// file attributes
NULL // handle
of file with attributes to copy
);
那么如果需要打开COM10以上的串口,就需要把第一个参数从原来的“COM10”改为“////.//COM10”,就能打开成功了。
笔者试验了一下,如果打开COM1的话,也可以使用“////.//COM1”。所以可以把传入的参数变为"////.//"+Port。