检测Winform C#应用程序中是否从PC拔出任何USB的事件

时间:2018-08-18 16:13:19

标签: c# events usb system.management

我正在尝试检测事件是否通过Winform C#应用程序从PC上拔出任何model.fit(xs, ys, { callbacks: { onTrainBegin: async () => { console.log("onTrainBegin") }, onTrainEnd: async (epoch, logs) => { console.log("onTrainEnd" + epoch + JSON.stringify(logs)) }, onEpochBegin: async (epoch, logs) => { console.log("onEpochBegin" + epoch + JSON.stringify(logs)) }, onEpochEnd: async (epoch, logs) => { console.log("onEpochEnd" + epoch + JSON.stringify(logs)) }, onBatchBegin: async (epoch, logs) => { console.log("onBatchBegin" + epoch + JSON.stringify(logs)) }, onBatchEnd: async (epoch, logs) => { console.log("onBatchEnd" + epoch + JSON.stringify(logs)) } } }) 。我在互联网上发现了几种方法stackoverflow:

usb

结果是我什么都不输出。

第二次尝试没有任何结果,或者using System; using System.Management; namespace USB { class Program { public enum EventType { Inserted = 2, Removed = 3 } static void Main(string[] args) { ManagementEventWatcher watcher = new ManagementEventWatcher(); WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 or EventType = 3"); watcher.EventArrived += (s, e) => { string driveName = e.NewEvent.Properties["DriveName"].Value.ToString(); EventType eventType = (EventType)(Convert.ToInt16(e.NewEvent.Properties["EventType"].Value)); string eventName = Enum.GetName(typeof(EventType), eventType); Console.WriteLine("{0}: {1} {2}", DateTime.Now, driveName, eventName); }; watcher.Query = query; watcher.Start(); Console.ReadKey(); } } } 行出现异常:

  

“ System.InvalidCastException”类型的异常发生在   USB.exe,但未用用户代码处理

ManagementBaseObject mbo = (ManagementBaseObject)pdData.Value;

或这种方式,但我不太了解namespace USB { class Program { static void Main(string[] args) { var watcher = new ManagementEventWatcher(); var query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2"); watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcher.Query = query; watcher.Start(); Console.ReadLine(); } static void watcher_EventArrived(object sender, EventArrivedEventArgs e) { bool bUSBEvent = false; foreach (PropertyData pdData in e.NewEvent.Properties) { ManagementBaseObject mbo = (ManagementBaseObject)pdData.Value; if (mbo != null) { foreach (PropertyData pdDataSub in mbo.Properties) { if (pdDataSub.Name == "InterfaceType" && pdDataSub.Value.ToString() == "USB") { bUSBEvent = true; break; } } if (bUSBEvent) { if (e.NewEvent.ClassPath.ClassName == "__InstanceCreationEvent") { Console.WriteLine("USB was plugged in"); } else if (e.NewEvent.ClassPath.ClassName == "__InstanceDeletionEvent") { Console.WriteLine("USB was plugged out"); } } } } } } } 必须是什么:

msScope

在这一过程中,我不确定如何处理事件本身:

namespace USB
{
    class Program
    {
        static void Main(string[] args)
        {
            WqlEventQuery weqQuery = new WqlEventQuery();
            weqQuery.EventClassName = "__InstanceOperationEvent";
            weqQuery.WithinInterval = new TimeSpan(0, 0, 3);
            weqQuery.Condition = @"TargetInstance ISA 'Win32_DiskDrive'";

            var m_mewWatcher = new ManagementEventWatcher();
            m_mewWatcher = new ManagementEventWatcher(msScope, weqQuery);
            m_mewWatcher.EventArrived += new EventArrivedEventHandler(m_mewWatcher_EventArrived);
            m_mewWatcher.Start();

            Console.ReadLine();
        }

        static void m_mewWatcher_EventArrived(object sender, EventArrivedEventArgs e)
        {
            bool bUSBEvent = false;
            foreach (PropertyData pdData in e.NewEvent.Properties)
            {
                ManagementBaseObject mbo = (ManagementBaseObject)pdData.Value;
                if (mbo != null)
                {
                    foreach (PropertyData pdDataSub in mbo.Properties)
                    {
                        if (pdDataSub.Name == "InterfaceType" && pdDataSub.Value.ToString() == "USB")
                        {
                            bUSBEvent = true;
                            break;
                        }
                    }

                    if (bUSBEvent)
                    {
                        if (e.NewEvent.ClassPath.ClassName == "__InstanceCreationEvent")
                        {
                            Console.WriteLine("USB was plugged in");
                        }
                        else if (e.NewEvent.ClassPath.ClassName == "__InstanceDeletionEvent")
                        {
                            Console.WriteLine("USB was plugged out");
                        }
                    }
                }
            }
        }  
    }
}

此外,我已经在表单应用程序中尝试过此方法,但是输出却一无所获:

using System;
using System.Management;
using System.ComponentModel;

namespace USB
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine();
            Console.ReadLine();
        }

       private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e)
         {
             ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
             foreach (var property in instance.Properties)
             {
                 Console.WriteLine(property.Name + " = " + property.Value);
             }
         }

         private void DeviceRemovedEvent(object sender, EventArrivedEventArgs e)
         {
             ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
             foreach (var property in instance.Properties)
             {
                 Console.WriteLine(property.Name + " = " + property.Value);
             }
         }

         private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
         {
             WqlEventQuery insertQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");

             ManagementEventWatcher insertWatcher = new ManagementEventWatcher(insertQuery);
             insertWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent);
             insertWatcher.Start();

             WqlEventQuery removeQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");
             ManagementEventWatcher removeWatcher = new ManagementEventWatcher(removeQuery);
             removeWatcher.EventArrived += new EventArrivedEventHandler(DeviceRemovedEvent);
             removeWatcher.Start();

             System.Threading.Thread.Sleep(20000000);
         }
    }
}

并以这种方式得到相同的结果:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.IO;

namespace USB
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
           Console.WriteLine( GetConnectedDevices());
           textBox1.Text = String.Join(Environment.NewLine, GetConnectedDevices());
        }

        public static List<System.IO.DriveInfo> GetConnectedDevices()
        {
            System.IO.DriveInfo[] myDrives = System.IO.DriveInfo.GetDrives();
            List<System.IO.DriveInfo> Drives = new List<System.IO.DriveInfo>();
            return myDrives.Where(info => (info.DriveType == System.IO.DriveType.Removable && info.IsReady)).ToList();
        }
    }
}

0 个答案:

没有答案