Click here to Skip to main content
16,017,608 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Good day Forum Family. Kindly help me with a way to detect when hardware connected to serial com port is (disconnected)removed? I have tried the code below but it is not working or firing.
C#
private void scanningPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
        MessageBox.Show("Hardware Removed");
}
Posted
Updated 30-Aug-14 3:41am
v2

It's not too bad: use the SerialPort.http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.pinchanged(v=vs.110).aspx[^] event and look at the SerialPinChange[^] enum DsrChanged value.
This is connected to a physical pin on the serial port which is high to indicate the equipment is ready. When you unplug the device, the pin should fall and the event should be triggered.
 
Share this answer
 
Comments
Admire Mhlaba 30-Aug-14 9:59am    
Thank you Griff but the event is not firing.
OriginalGriff 30-Aug-14 10:08am    
Have you checked the serial connector you are using raises it in the first place?
OriginalGriff 30-Aug-14 10:27am    
:sigh:
Yes, but did you check if the device you used raises the physical pin?
OriginalGriff 30-Aug-14 10:44am    
You could look at the SerialPort.DsrHolding property?
Admire Mhlaba 30-Aug-14 10:48am    
scanningPort.DsrHolding returns false.
Try this code example. I didn't test it but maybe it works. Use WMI and look at this Win32_SerialPort class How to detect when hardware connected to serial com port is (disconnected)removed?[^]


I have created this example for detecting the usb, local disk, cd device For example listing, adding, removing and modification for Win32_LogicalDisk.

Create a custom class for Serial device that containing the device informations. You also need to crate a new event enum for serial device events. You can change the target class name for your own using.

C#
public enum Win32_LogicalDisk_EventTypeEnum
    {
        Creation,
        Deletion,
        Modification
    };

    public enum Win32_LogicalDisk_DriveTypeEnum
    {
        Unknown = 0,
        NoRootDirectory = 1,
        RemovableDisk = 2,
        LocalDisk = 3,
        NetworkDrive = 4,
        CompactDisc = 5,
        RAMDisk = 6
    };

    public class Win32_LogicalDisk : IEquatable<Win32_LogicalDisk>
    {
        public UInt32 DriveType { get; set; }
        public UInt64 Size { get; set; }
        public UInt64 FreeSpace { get; set; }
        public string Name { get; set; }
        public string DeviceID { get; set; }
        public string FileSystem { get; set; }
        public string VolumeName { get; set; }
        public string VolumeSerialNumber { get; set; }
        public string Description { get; set; }
        public Win32_LogicalDisk_EventTypeEnum EventType { get; set; }
        public Win32_LogicalDisk_DriveTypeEnum GetDriveType
        {
            get { return (Win32_LogicalDisk_DriveTypeEnum)this.DriveType; }
        }

        public bool Equals(Win32_LogicalDisk other)
        {
            if (other == null)
                return false;

            if (this.VolumeSerialNumber == other.VolumeSerialNumber)
                return true;
            else
                return false;
        }

        public override bool Equals(Object obj)
        {
            if (obj == null)
                return false;

            Win32_LogicalDisk diskObj = obj as Win32_LogicalDisk;
            if (diskObj == null)
                return false;
            else
                return Equals(diskObj);
        }

        public override int GetHashCode()
        {
            return this.VolumeSerialNumber.GetHashCode();
        }

        public static bool operator ==(Win32_LogicalDisk disk1, Win32_LogicalDisk disk2)
        {
            if ((object)disk1 == null || ((object)disk2) == null)
                return Object.Equals(disk1, disk2);

            return disk1.Equals(disk2);
        }

        public static bool operator !=(Win32_LogicalDisk disk1, Win32_LogicalDisk disk2)
        {
            if (disk1 == null || disk2 == null)
                return !Object.Equals(disk1, disk2);

            return !(disk1.Equals(disk2));
        }
    }


and the other task object class:

using System;
using System.Management;
using FileGeo.CommonObjects;
using FileGeo.Operational.TaskThreadingModel;

namespace FileGeo.TaskOperations
{
    public class LogicalDiskAddedEventArgs : EventArgs, IDisposable
    {
        #region Constructor

        public LogicalDiskAddedEventArgs(
            Win32_LogicalDisk LogicalDisk)
        {
            this.LogicalDisk = LogicalDisk;
        }

        #endregion

        #region Property

        /// <summary>
        /// Gets the logical disk added to the system.
        /// </summary>
        public Win32_LogicalDisk LogicalDisk { get; private set; }

        #endregion

        #region IDisposable Members

        void IDisposable.Dispose()
        {
            GC.SuppressFinalize(this);
        }

        #endregion
    }

    public class LogicalDiskRemovedEventArgs : EventArgs, IDisposable
    {
        #region Constructor

        public LogicalDiskRemovedEventArgs(
            Win32_LogicalDisk LogicalDisk)
        {
            this.LogicalDisk = LogicalDisk;
        }

        #endregion

        #region Property

        /// <summary>
        /// Gets the logical disk removed from the system.
        /// </summary>
        public Win32_LogicalDisk LogicalDisk { get; private set; }

        #endregion

        #region IDisposable Members

        void IDisposable.Dispose()
        {
            GC.SuppressFinalize(this);
        }

        #endregion
    }

    public class LogicalDiskModifiedEventArgs : EventArgs, IDisposable
    {
        #region Constructor

        public LogicalDiskModifiedEventArgs(
            Win32_LogicalDisk OldLogicalDisk, Win32_LogicalDisk ModifiedLogicalDisk)
        {
            this.OldLogicalDisk = OldLogicalDisk;
            this.ModifiedLogicalDisk = ModifiedLogicalDisk;
        }

        #endregion

        #region Property

        /// <summary>
        /// Gets the old logical disk from the system.
        /// </summary>
        public Win32_LogicalDisk OldLogicalDisk { get; private set; }

        /// <summary>
        /// Gets the modified logical disk from the system.
        /// </summary>
        public Win32_LogicalDisk ModifiedLogicalDisk { get; private set; }

        #endregion

        #region IDisposable Members

        void IDisposable.Dispose()
        {
            GC.SuppressFinalize(this);
        }

        #endregion
    }

    /// <summary>
    /// This example shows synchronous consumption of events. The task thread is blocked while waiting for events.
    /// </summary>
    public class Win32_LogicalDiskManagementTask : TaskWrapperBase
    {
        #region Events

        public event EventHandler<LogicalDiskAddedEventArgs> LogicalDiskAdded;
        public event EventHandler<LogicalDiskRemovedEventArgs> LogicalDiskRemoved;
        public event EventHandler<LogicalDiskModifiedEventArgs> LogicalDiskModified;

        #endregion

        #region Constructor

        public Win32_LogicalDiskManagementTask(System.Windows.Forms.Control invokeContext)
        {
            this.InvokeContext = invokeContext;
        }

        #endregion

        public System.Windows.Forms.Control InvokeContext { get; private set; }

        /// <summary>
        /// Bu kanal işleminin sonlanması beklenmeyecek, client sonlandığında bu kanal da kapatılsın.(Uygulama kapanana kadar kendisi sonlanabilir)
        /// </summary>
        protected override bool IsBlockUntilTerminated
        {
            get
            {
                return false;
            }
        }

        public override string OperationName
        {
            get
            {
                return "Win32_LogicalDisk management operation";
            }
        }

        public override void Dispose()
        {
            System.GC.SuppressFinalize(this);
        }

        protected override void DoTask()
        {
            ManagementEventWatcher watcher = null;
            try
            {
                // Create event query to be notified within 1 second of a change in a service.
                WqlEventQuery query = new WqlEventQuery("__InstanceOperationEvent", new TimeSpan(0, 0, 1),
                    "TargetInstance isa \"Win32_LogicalDisk\"");
                // Initialize an event watcher and subscribe to events that match this query.
                watcher = new ManagementEventWatcher(query);
                do
                {
                    // Initialize the logical disks to the default values.
                    Win32_LogicalDisk previousDisk, targetDisk = null;
                    // Block until the next event occurs.
                    ManagementBaseObject o = watcher.WaitForNextEvent();
                    switch (o.ClassPath.ClassName)
                    {
                        case "__InstanceCreationEvent":
                            targetDisk = InvokeLogicalDisk(o["TargetInstance"] as ManagementBaseObject,
                                Win32_LogicalDisk_EventTypeEnum.Creation);
                            if (targetDisk != null && InvokeContext.IsHandleCreated)
                            {
                                using (LogicalDiskAddedEventArgs ea = new LogicalDiskAddedEventArgs(targetDisk))
                                {
                                    // Fire notification event on the user interface thread.
                                    InvokeContext.Invoke(
                                        new EventHandler<LogicalDiskAddedEventArgs>(OnLogicalDiskAdded),
                                        new object[] { this, ea });
                                }
                            }
                            break;
                        case "__InstanceDeletionEvent":
                            targetDisk = InvokeLogicalDisk(o["TargetInstance"] as ManagementBaseObject,
                                Win32_LogicalDisk_EventTypeEnum.Deletion);
                            if (targetDisk != null && InvokeContext.IsHandleCreated)
                            {
                                using (LogicalDiskRemovedEventArgs ea = new LogicalDiskRemovedEventArgs(targetDisk))
                                {
                                    // Fire notification event on the user interface thread.
                                    InvokeContext.Invoke(
                                        new EventHandler<LogicalDiskRemovedEventArgs>(OnLogicalDiskRemoved),
                                        new object[] { this, ea });
                                }
                            }
                            break;
                        case "__InstanceModificationEvent":
                            previousDisk = InvokeLogicalDisk(o["PreviousInstance"] as ManagementBaseObject,
                                Win32_LogicalDisk_EventTypeEnum.Modification);
                            targetDisk = InvokeLogicalDisk(o["TargetInstance"] as ManagementBaseObject,
                                Win32_LogicalDisk_EventTypeEnum.Modification);
                            if (previousDisk != null && targetDisk != null && InvokeContext.IsHandleCreated)
                            {
                                using (LogicalDiskModifiedEventArgs ea = new LogicalDiskModifiedEventArgs(previousDisk, targetDisk))
                                {
                                    // Fire notification event on the user interface thread.
                                    InvokeContext.Invoke(
                                        new EventHandler<LogicalDiskModifiedEventArgs>(OnLogicalDiskModified),
                                        new object[] { this, ea });
                                }
                            }
                            break;
                    }
                } while (true);
            }
            catch (Exception)
            {
                if (watcher != null)
                {
                    // Cancel the subscription.
                    watcher.Stop();
                    // Dispose the watcher object and release it.
                    watcher.Dispose();
                    watcher = null;
                }
                throw;
            }
        }

        #region Helper Methods

        private Win32_LogicalDisk InvokeLogicalDisk(ManagementBaseObject obj, Win32_LogicalDisk_EventTypeEnum eventType)
        {
            Win32_LogicalDisk result = null;
            if (obj != null)
            {
                result = new Win32_LogicalDisk() { EventType = eventType };
                result.DriveType = Convert.ToUInt32(obj["DriveType"]);
                result.Size = Convert.ToUInt64(obj["Size"]);
                result.FreeSpace = Convert.ToUInt64(obj["FreeSpace"]);
                result.Name = (obj["Name"] ?? "").ToString();
                result.DeviceID = (obj["DeviceID"] ?? "").ToString();
                result.FileSystem = (obj["FileSystem"] ?? "").ToString();
                result.VolumeName = (obj["VolumeName"] ?? "").ToString();
                result.VolumeSerialNumber = (obj["VolumeSerialNumber"] ?? "").ToString();
                result.Description = (obj["Description"] ?? "").ToString();
            }
            return result;
        }

        private void OnLogicalDiskAdded(object sender, LogicalDiskAddedEventArgs e)
        {
            if (LogicalDiskAdded != null)
                LogicalDiskAdded(sender, e);
        }

        private void OnLogicalDiskRemoved(object sender, LogicalDiskRemovedEventArgs e)
        {
            if (LogicalDiskRemoved != null)
                LogicalDiskRemoved(sender, e);
        }

        private void OnLogicalDiskModified(object sender, LogicalDiskModifiedEventArgs e)
        {
            if (LogicalDiskModified != null)
                LogicalDiskModified(sender, e);
        }

        #endregion
    }
}
 
Share this answer
 
Comments
Admire Mhlaba 30-Aug-14 14:34pm    
thank you but the code was tricky for me to understand. Kindly help me improve the code I posted as a solution to display messages as this :

"USB Serial (COM4)" was plugged.

"USB Serial (COM4)" was unplugged.
using System.Management;

namespace UsbDection
{
    class Program
    {
        static ManagementEventWatcher watchingObect = null;
        static WqlEventQuery watcherQuery;
        static ManagementScope scope;
        static void Main(string[] args)
        {
            scope = new ManagementScope("root\\CIMV2");
            scope.Options.EnablePrivileges = true;

            AddInsetUSBHandler();
            AddRemoveUSBHandler();

            for (; ; ) ;
        }

        public static void AddRemoveUSBHandler()
        {

            try
            {
                USBWatcherSetUp("__InstanceDeletionEvent");
                watchingObect.EventArrived += new EventArrivedEventHandler(USBRemoved);
                watchingObect.Start();

            }

            catch (Exception e)
            {

                Console.WriteLine(e.Message);
                if (watchingObect != null)
                    watchingObect.Stop();

            }

        }

        static void AddInsetUSBHandler()
        {

            try
            {
                USBWatcherSetUp("__InstanceCreationEvent");
                watchingObect.EventArrived += new EventArrivedEventHandler(USBAdded);
                watchingObect.Start();

            }
            catch (Exception e)
            {

                Console.WriteLine(e.Message);
                if (watchingObect != null)
                    watchingObect.Stop();

            }

        }

        private static void USBWatcherSetUp(string eventType)
        {
            
            watcherQuery = new WqlEventQuery();
            watcherQuery.EventClassName = eventType;
            watcherQuery.WithinInterval = new TimeSpan(0, 0, 2);
            watcherQuery.Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'";
            watchingObect = new ManagementEventWatcher(scope, watcherQuery);
        }

        public static void USBAdded(object sender, EventArgs e)
        {

            Console.WriteLine("A USB device inserted");

        }

        public static void USBRemoved(object sender, EventArgs e)
        {

            Console.WriteLine("A USB device removed");

        }
    }

}




The above code is working but I need help getting the name of the device added or removed.
 
Share this answer
 
v2
Comments
Admire Mhlaba 30-Aug-14 14:32pm    
Kindly help me improve the code I posted as a solution to display messages as this :

"USB Serial (COM4)" was plugged.

"USB Serial (COM4)" was unplugged.
[no name] 31-Aug-14 0:30am    
This answer does not match the question. Others have answered the specific question you asked. You are now talking about removing USB (pnp) devices and not devices attached to serial ports which is what your question referred to. If this is the answer you want then the question should be amended. You also seem to have accepted your own answer which you say does not work. This is not a good way to get help.

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