Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3428468
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T06:57:46+00:00 2026-05-18T06:57:46+00:00

I am interfacing with a USB-to-serial port that can be inserted or removed at

  • 0

I am interfacing with a USB-to-serial port that can be inserted or removed at any time. I’ve found that I can use WMI (particularly with the use of WMI Code Creator) to query for device changes in the PC.

In the generated snippet below, the Win32_DeviceChangeEvent is subscribed to. However, this event doesn’t reveal which device (e.g. USB, serial port, etc) caused the event. Is there a way to only receive notifications when serial ports are inserted or removed?

To clarify, the point of the code is not to detect opening/closing of serial ports, it is to detect whether a new port has been added to the machine or a previous port was removed.

using System;
using System.Management;
using System.Windows.Forms;

namespace WMISample
{
    public class WMIReceiveEvent
    {
        public WMIReceiveEvent()
        {
            try
            {
                WqlEventQuery query = new WqlEventQuery(
                    "SELECT * FROM Win32_DeviceChangeEvent");

                ManagementEventWatcher watcher = new ManagementEventWatcher(query);
                Console.WriteLine("Waiting for an event...");

                watcher.EventArrived += 
                    new EventArrivedEventHandler(
                    HandleEvent);

                // Start listening for events
                watcher.Start();

                // Do something while waiting for events
                System.Threading.Thread.Sleep(10000);

                // Stop listening for events
                watcher.Stop();
                return;
            }
            catch(ManagementException err)
            {
                MessageBox.Show("An error occurred while trying to receive an event: " + err.Message);
            }
        }

        private void HandleEvent(object sender,
            EventArrivedEventArgs e)
        {
            Console.WriteLine("Win32_DeviceChangeEvent event occurred.");
        }

        public static void Main()
        {
            WMIReceiveEvent receiveEvent = new WMIReceiveEvent();
            return;
        }

    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T06:57:46+00:00Added an answer on May 18, 2026 at 6:57 am

    I ended up using WMI and @Hans’ advice to check what serial ports are new/missing.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Diagnostics.Contracts;
    using System.IO.Ports;
    using System.Management;
    
    public static class SerialPortService
    {
        private static SerialPort _serialPort;
    
        private static string[] _serialPorts;
    
        private static ManagementEventWatcher arrival;
    
        private static ManagementEventWatcher removal;
    
        static SerialPortService()
        {
            _serialPorts = GetAvailableSerialPorts();
            MonitorDeviceChanges();
        }
    
        /// <summary>
        /// If this method isn't called, an InvalidComObjectException will be thrown (like below):
        /// System.Runtime.InteropServices.InvalidComObjectException was unhandled
        ///Message=COM object that has been separated from its underlying RCW cannot be used.
        ///Source=mscorlib
        ///StackTrace:
        ///     at System.StubHelpers.StubHelpers.StubRegisterRCW(Object pThis, IntPtr pThread)
        ///     at System.Management.IWbemServices.CancelAsyncCall_(IWbemObjectSink pSink)
        ///     at System.Management.SinkForEventQuery.Cancel()
        ///     at System.Management.ManagementEventWatcher.Stop()
        ///     at System.Management.ManagementEventWatcher.Finalize()
        ///InnerException: 
        /// </summary>
        public static void CleanUp()
        {
            arrival.Stop();
            removal.Stop();
        }
    
        public static event EventHandler<PortsChangedArgs> PortsChanged;
    
        private static void MonitorDeviceChanges()
        {
            try
            {
                var deviceArrivalQuery = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
                var deviceRemovalQuery = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3");
    
                arrival = new ManagementEventWatcher(deviceArrivalQuery);
                removal = new ManagementEventWatcher(deviceRemovalQuery);
    
                arrival.EventArrived += (o, args) => RaisePortsChangedIfNecessary(EventType.Insertion);
                removal.EventArrived += (sender, eventArgs) => RaisePortsChangedIfNecessary(EventType.Removal);
    
                // Start listening for events
                arrival.Start();
                removal.Start();
            }
            catch (ManagementException err)
            {
    
            }
        }
    
        private static void RaisePortsChangedIfNecessary(EventType eventType)
        {
            lock (_serialPorts)
            {
                var availableSerialPorts = GetAvailableSerialPorts();
                if (!_serialPorts.SequenceEqual(availableSerialPorts))
                {
                    _serialPorts = availableSerialPorts;
                    PortsChanged.Raise(null, new PortsChangedArgs(eventType, _serialPorts));
                }
            }
        }
    
        public static string[] GetAvailableSerialPorts()
        {
            return SerialPort.GetPortNames();
        }
    }
    
    public enum EventType
    {
        Insertion,
        Removal,
    }
    
    public class PortsChangedArgs : EventArgs
    {
        private readonly EventType _eventType;
    
        private readonly string[] _serialPorts;
    
        public PortsChangedArgs(EventType eventType, string[] serialPorts)
        {
            _eventType = eventType;
            _serialPorts = serialPorts;
        }
    
        public string[] SerialPorts
        {
            get
            {
                return _serialPorts;
            }
        }
    
        public EventType EventType
        {
            get
            {
                return _eventType;
            }
        }
    }
    

    The MonitorDeviceChanges method actually sees all device changes (like Device Manager), but checking the serial ports allows us to only raise an event when those have changed.

    To use the code, simply subscribe to the PortsChanged event, e.g. SerialPortService.PortsChanged += (sender1, changedArgs) => DoSomethingSerial(changedArgs.SerialPorts);

    Oh, and the .Raise method is just an extension method I picked up somewhere:

    /// <summary>
    /// Tell subscribers, if any, that this event has been raised.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="handler">The generic event handler</param>
    /// <param name="sender">this or null, usually</param>
    /// <param name="args">Whatever you want sent</param>
    public static void Raise<T>(this EventHandler<T> handler, object sender, T args) where T : EventArgs
    {
        // Copy to temp var to be thread-safe (taken from C# 3.0 Cookbook - don't know if it's true)
        EventHandler<T> copy = handler;
        if (copy != null)
        {
            copy(sender, args);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm interfacing with a payment gateway and not having any luck with Net::SSLeay and
In a project I am interfacing between C++ and a C library that uses
I am developing a wrapper for a third party function library that is interfacing
We have several legacy components that interact with COM ports, USB etc. I would
Interfacing with legacy code, and I've got something like this: Event.observe(some_form, 'submit', [some anonymous
I am interfacing with a server that requires that data sent to it is
I am using Delphi 6 Professional. I am interfacing with a DLL libraty that
Our application is interfacing with a lot of web services these days. We have
I am working on an in-house tool for interfacing to a database. My current
There are many types of external dependencies. Interfacing with external applications, components or services

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.