void UpdateSettings() { lock (_lock) { // This assumes the handle is acquired. if (!_settingsChanged) { return; } _settingsChanged = false; var dcb = new NativeMethods.DCB(); dcb.DCBlength = Marshal.SizeOf(typeof(NativeMethods.DCB)); if (!NativeMethods.GetCommState(_handle, ref dcb)) { int hr = Marshal.GetHRForLastWin32Error(); throw DeviceException.CreateIOException(Device, "Failed to get serial state.", hr); } int baudRate = _ser.BaudRate; int dataBits = _ser.DataBits; var parity = _ser.Parity; int stopBits = _ser.StopBits; SetDcbDefaults(ref dcb); dcb.BaudRate = checked ((uint)baudRate); dcb.ByteSize = checked ((byte)_ser.DataBits); dcb.Parity = parity == SerialParity.Even ? NativeMethods.EVENPARITY : parity == SerialParity.Odd ? NativeMethods.ODDPARITY : NativeMethods.NOPARITY; dcb.StopBits = stopBits == 2 ? NativeMethods.TWOSTOPBITS : NativeMethods.ONESTOPBIT; if (!NativeMethods.SetCommState(_handle, ref dcb)) { int hr = Marshal.GetHRForLastWin32Error(); throw DeviceException.CreateIOException(Device, "Failed to set serial state.", hr); } var purgeFlags = NativeMethods.PURGE_RXABORT | NativeMethods.PURGE_RXCLEAR | NativeMethods.PURGE_TXABORT | NativeMethods.PURGE_TXCLEAR; if (!NativeMethods.PurgeComm(_handle, purgeFlags)) { int hr = Marshal.GetHRForLastWin32Error(); throw DeviceException.CreateIOException(Device, "Failed to purge serial port.", hr); } } }
static void SetDcbDefaults(ref NativeMethods.DCB dcb) { dcb.fFlags = 0; dcb.fBinary = true; }