public void Open(string name, int speed) { var portDcb = new DCB(); var commTimeouts = new COMMTIMEOUTS(); _hPort = Win32.CreateFile($@"\\.\{name}", Win32.GENERIC_READ | Win32.GENERIC_WRITE, 0, IntPtr.Zero, Win32.OPEN_EXISTING, 0, IntPtr.Zero); if (_hPort == (IntPtr)Win32.INVALID_HANDLE_VALUE) { throw new Win32Exception(Marshal.GetLastWin32Error()); } commTimeouts.ReadIntervalTimeout = 0; commTimeouts.ReadTotalTimeoutConstant = 1500; commTimeouts.ReadTotalTimeoutMultiplier = 15; commTimeouts.WriteTotalTimeoutConstant = 1500; commTimeouts.WriteTotalTimeoutMultiplier = 15; Win32.GetCommState(_hPort, ref portDcb); portDcb.BaudRate = speed; if (!Win32.SetCommState(_hPort, ref portDcb)) { throw new IOException("Bad COM settings"); } if (!Win32.SetCommTimeouts(_hPort, ref commTimeouts)) { throw new IOException("Bad timeout settings"); } }
internal static extern Boolean SetCommTimeouts(IntPtr hFile, [In] ref COMMTIMEOUTS lpCommTimeouts);
internal static extern Boolean BuildCommDCBAndTimeouts(String lpDef, ref DCB lpDCB, ref COMMTIMEOUTS lpCommTimeouts);
internal static extern Boolean GetCommTimeouts(IntPtr hFile, out COMMTIMEOUTS lpCommTimeouts);