用CreateFile打开COM10以上的串口

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yu__jia/article/details/52862020

在VS2010上用CreateFile打开串口,代码如下:

[cpp]  view plain  copy
  1. HANDLE m_hComm=CreateFile(Port,GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,0,0);  
  2. if(m_hComm==INVALID_HANDLE_VALUE )  
  3. {  
  4.     AfxMessageBox(_T("无法打开端口!请检查是否已被占用。"));  
  5.     return FALSE;  
  6. }  

 

其中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]);




 

猜你喜欢

转载自blog.csdn.net/yu__jia/article/details/52862020
今日推荐