设置串口RS232端口设置;在SerialPort类的C#替代品中有哪些?

时间:2010-06-01 10:51:43

标签: .net serial-port

在我的.NET应用程序中,我需要实现与此C ++托管代码等效的串行端口设置:

::SetCommMask(m_hCOMM, EV_RXCHAR);  
::SetupComm(m_hCOMM, 9*2*128*10, 400);
::PurgeComm(m_hCOMM, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR);

COMMTIMEOUTS timeOut;
timeOut.ReadIntervalTimeout        = 3;
timeOut.ReadTotalTimeoutConstant   = 3;
timeOut.ReadTotalTimeoutMultiplier = 1; 
timeOut.WriteTotalTimeoutConstant  = 0;
timeOut.WriteTotalTimeoutMultiplier= 0;
int nRet= ::SetCommTimeouts(m_hCOMM, &timeOut); 

::EscapeCommFunction(m_hCOMM, SETDTR);  
::EscapeCommFunction(m_hCOMM, SETRTS);      

DCB dcb;
memset(&dcb, 0, sizeof(DCB));
dcb.BaudRate= m_nSpeed; 
dcb.ByteSize= 8;
dcb.fParity = FALSE;
dcb.Parity  = NOPARITY;
dcb.StopBits= ONESTOPBIT;
dcb.fBinary = TRUE;


dcb.fDsrSensitivity= FALSE; 

dcb.fOutxDsrFlow= FALSE;        
dcb.fOutxCtsFlow= FALSE;            


dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
dcb.fRtsControl = RTS_CONTROL_TOGGLE;

nRet= ::SetCommState(m_hCOMM, &dcb);

有可能吗?我该如何处理这个问题?是否有任何(优选的免费)库允许这种低级串口控制或者我应该在Win32 api之上创建自己的包装器? 任何人做过类似的事情,或者想知道如何用.net“粘合”win32串口api,以便我可以使用整洁的.NET DataReceived()事件?或者我可以创建.NET SerialPort实例,然后使用托管API修改它?

1 个答案:

答案 0 :(得分:0)

.NET SerialPort class拥有您需要的大部分内容。

p = SerialPort.SerialPort(); //use whichever constructor you need

p.DiscarInBuffer();
p.DiscardOutbuffer();
p.ReadBufferSize = 9*2*128*10;
p.WriteBufferSize = 400;


p.ReadTimeout = 10; //not exactly equivalent to COMMTIMEOUTS
p.WriteTimeout = 0;

p.DtrEnable = true;
p.RtsEnable = true;

p.BaudRate = m_nSpeed;
p.DataBits = 8;
p.Parity = Parity.None;
p.StopBits = StopBits.One;

//I think DSR and CTS states are pollable by app but ignored by driver