Click here to Skip to main content
15,887,946 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do I get the RS232 ports that are being used? This is the code that I came up with.

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;
using System.Management;

namespace Detect_USB2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            SerialPort ComPort = new SerialPort();

            chkSP();
        }
        private void chkSP()
        {
            ManagementObjectSearcher searchType = new ManagementObjectSearcher("SELECT * FROM Win32_SerialPort");

            foreach (ManagementObject moDiskete in searchType.Get())
            {
                if (!listBox1.Items.Contains(moDiskete["Name"]))
                {
                    
                    listBox1.Items.Add(moDiskete["Name"].ToString());

                }
            }            
        }
        private void MyTimer_Tick(object sender, EventArgs e)
        {
         listBox1.Items.Clear();
            chkSP(); 
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            Timer MyTimer = new Timer();
            MyTimer.Interval = (5 * 1000); // 1 mins
            MyTimer.Tick += new EventHandler(MyTimer_Tick);
            
            MyTimer.Start();
        }  
    }
}
Posted

1 solution

Start with SerialPort.GetPortNames(v=vs.110).aspx[^] to find all available ports to the system, then you pretty much have to try to Open each one in a try...catch block and use only those that don't fail. There is no "IsFree" property for a comport and "IsOpen" only tracks ports within the current app - if it's open in a different application (and thus not free) IsOpen will still return false.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900