如何检测连接到串行COM端口的硬件何时被删除? [英] How to detect when hardware connected to serial com port is (disconnected)removed?

查看:89
本文介绍了如何检测连接到串行COM端口的硬件何时被删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天论坛家庭。请帮我一个方法来检测连接到串行COM端口的硬件何时(断开连接)被删除?我已尝试过下面的代码,但它无法正常工作或触发。

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.

private void scanningPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
        MessageBox.Show("Hardware Removed");
}

推荐答案

这还不错:使用SerialPort。 http://msdn.microsoft.com/en-us/library/system.io.ports .serialport.pinchanged(v = vs.110).aspx [ ^ ]事件并查看 SerialPinChange [ ^ ]枚举DsrChanged值。

这与物理连接串口上的引脚为高电平表示设备已准备就绪。当您拔下设备时,引脚应该掉落并且应该触发事件。
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.


试试这个代码示例。我没有测试它,但也许它有效。使用WMI并查看此Win32_SerialPort类如何检测何时连接到串行COM端口的硬件是(已断开连接)已删除? [ ^ ]





我创建了这个用于检测usb,本地磁盘,cd设备的示例例如列出,添加,删除和修改Win32_LogicalDisk。



为包含设备的串行设备创建自定义类信息。您还需要为串行设备事件创建新的事件枚举。您可以更改自己使用的目标类名。



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.

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
    }
}


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.


这篇关于如何检测连接到串行COM端口的硬件何时被删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆