コード例 #1
0
        private static void QueryComPortInformation(out List <ComPortInformation> infos)
        {
            infos = new List <ComPortInformation>();
            using (var searcher = new ManagementObjectSearcher
                                      ("SELECT * FROM WIN32_SerialPort"))
            {
                var ports = searcher.Get().Cast <ManagementBaseObject>().ToList();

                foreach (ManagementBaseObject item in ports)
                {
                    ComPortInformation info = new ComPortInformation()
                    {
                        DeviceId      = (string)item["DeviceID"],
                        DeviceCaption = (string)item["Caption"]
                    };

                    if (!infos.Contains(info))
                    {
                        infos.Add(info);
                    }
                }
            }
        }
コード例 #2
0
ファイル: MainWindow.xaml.cs プロジェクト: cbries/utilities
        private void OpenCom()
        {
            TxtLogView.Clear();
            ComPortInformation comInfo = CmbComPorts.SelectedItem as ComPortInformation;

            if (comInfo == null)
            {
                throw new Exception("COM Port is invalid");
            }
            Log("Open COM Port: " + comInfo.DeviceCaption);
            CloseCom();
            _serialPort = new SerialPort(comInfo.DeviceId, 9600, Parity.None);
            _serialPort.DataReceived  += SerialPortOnDataReceived;
            _serialPort.ErrorReceived += SerialPortOnErrorReceived;
            try
            {
                _serialPort.Open();
            }
            catch (Exception ex)
            {
                Log(string.Format("Open failed: {0}", ex.Message));
                CloseCom();
            }
        }