开发者

Setting serial RS232 port settings; any in C# alternatives to SerialPort class?

In my .NET application I need to achieve serial port setup equivalent to this C++ managed code:

::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.Re开发者_JS百科adTotalTimeoutMultiplier = 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);

Is it possible at all? How do I approach this problem? Are there any (preferable free) libraries that allow such low level serial port control or should I create my own wrapper on top of Win32 api? Anyone did anything similar or has an idea how to 'glue' win32 serial port api with .net so that I can use neat .NET DataReceived() events ? Or maybe I can create .NET SerialPort instance and then modify it using managed API?


The .NET SerialPort class has most of what you need.

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 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜