在VS2010上用CreateFile打開串口,代碼如下:
- HANDLE m_hComm=CreateFile(Port,GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,0,0);
- if(m_hComm==INVALID_HANDLE_VALUE )
- {
- AfxMessageBox(_T("無法打開端口!請檢查是否已被佔用。"));
- return FALSE;
- }
其中Port是LPCTSTR類型。
如果打開串口1,就傳給Port的值爲:“COM1”。
因項目需要,需要打開很多串口,發現以上函數到COM10以後就不能用了,始終不能打開串口。即調用CreateFile後,返回的m_hComm爲INVALID_HANDLE_VALUE。
在CSDN上查看了一下,原文如下:
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"。
if ((UARTNb=SendDlgItemMessage(IDC_COMBO_SERIAL,CB_GETCURSEL,0,0))>=SerialPort.NbUARTs)
return FALSE;
lstrcpy(SerialPort.FileName,L"\\\\.\\");
lstrcpy(SerialPort.FileName+4,SerialPort.UARTsName[UARTNb]);