I have this C++ code which I need to translate to C#.
*hDev = CreateFile(PortNameUNC, GENERIC_READ|GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(*hDev == INVALID_HANDLE_VALUE) return false ;
DCB *dcb = new DCB ;
memset(dcb, 0x00, sizeof(DCB)) ;
dcb->DCBlength = sizeof(DCB);
dcb->BaudRate = BaudRate;
dcb->Parity = Parity;
dcb->StopBits = StopBits;
dcb->ByteSize = ByteSize;
dcb->fBinary = TRUE;
dcb->fDsrSensitivity = 0;
dcb->fDtrControl = (DTR ? DTR_CONTROL_ENABLE : DTR_CONTROL_DISABLE) ;
dcb->fRtsControl = (RTS ? RTS_CONTROL_ENABLE : RTS_CONTROL_DISABLE) ;
dcb->fOutxCtsFlow = (CTS ? 1 : 0) ;
dcb->fOutxDsrFlow = (DSR ? 1 : 0) ;
dcb->fOutX = (XonnXoff ? 1 : 0) ;
dcb->fInX = 0 ;
I managed to translate most of it on C# using e.g.
m_port = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
But I am not sure how to set properties like DTR, RTS, CTS, DSR and Xonn/Xoff?
I found Dtr.Enable
and Rts.Enable
properties on SerialPort
, but what to do with other three? CTS, DSR and Xonn/Xoff? How to enable them?
EDIT: Also, here is my C# implementation of above. Have I correctly mapped the C++ code to C# as below? any feedback appreciated. especially the xon/xoff
flags and the dtr
and rts
?
public SerialPortHASP(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, bool dtr, bool rts, bool xonxoff)
{
m_port = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
// Set XonXoff if set
if (xonxoff)
m_port.Handshake = Handshake.XOnXOff;
// Set DTR/RTS
m_port.DtrEnable = dtr;
m_port.RtsEnable = rts;
// Open the port for communications
m_port.Open();
}
Best Answer
CTS and DSR are inputs so they can't be set from code. They can be checked by accessing the following properties; CtsHolding and DsrHolding.
XOnXOff is a flow control and can be set using the serial ports Handshake property.