コード例 #1
0
        private SerialPortFixer(string portName)
        {
            if (portName == null || !portName.StartsWith("COM", StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentException("Invalid Serial Port", nameof(portName));
            }

            SafeFileHandle file = SerialPortFixer.CreateFile("\\\\.\\" + portName, -1073741824, 0, IntPtr.Zero, 3, 1073741824, IntPtr.Zero);

            if (file.IsInvalid)
            {
                SerialPortFixer.WinIoError();
            }

            try
            {
                switch (SerialPortFixer.GetFileType(file))
                {
                case 0:
                case 2:
                    m_Handle = file;
                    InitializeDcb();
                    break;

                default:
                    throw new ArgumentException("Invalid Serial Port", nameof(portName));
                }
            }
            catch
            {
                file.Close();
                m_Handle = null;
                throw;
            }
        }
コード例 #2
0
        private void SetCommStateNative(ref SerialPortFixer.Dcb lpDcb)
        {
            var lpErrors = 0;
            var lpStat   = new SerialPortFixer.Comstat();

            for (var index = 0; index < 10; ++index)
            {
                if (!SerialPortFixer.ClearCommError(m_Handle, ref lpErrors, ref lpStat))
                {
                    SerialPortFixer.WinIoError();
                }

                if (SerialPortFixer.SetCommState(m_Handle, ref lpDcb))
                {
                    break;
                }

                if (index == 9)
                {
                    SerialPortFixer.WinIoError();
                }
            }
        }