简体   繁体   English

如何创建一个watcherprocess来检测可移动的USB设备?

[英]How to create a watcherprocess to detect a removeable USB Device?

I build a little script that checks if a USB Stick with a given Name ist plugged into the Computer, but now I want to build a service around this Script to watch if the Stick plugged in or not. 我构建了一个小脚本,用于检查具有给定名称的USB Stick是否已插入计算机,但现在我想围绕此脚本构建一个服务,以观察Stick是否插入。 At first I try to do this with the filewatcher and create a file on the Stick but if remove the stick from the pc and replugged the filewatcher dosent realize it. 起初我尝试用filewatcher执行此操作并在Stick上创建一个文件,但是如果从PC上取下棒并重新插入filewatcher dosent意识到它。 The following script check one time if the Stick is plugged in or not, but I need a script to loop this DriveInfo.GetDrive function. 以下脚本检查Stick是否插入一次,但我需要一个脚本来循环此DriveInfo.GetDrive函数。 I dont know if the best way is to buil a 10 second timer loop around this function or if there is any watcher class for removeable devices in the .NET Framework. 我不知道最好的方法是在这个函数周围建立一个10秒的定时器循环,或者.NET Framework中是否有可移动设备的观察者类。 Here comes the Script: 脚本来了:

public static void Main()
{
    Run();
}

public static void Run()
{                     
    var drives = DriveInfo.GetDrives()
        .Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);
    if (drives.Count() > 0)
    {
        foreach (var drive in drives)
        {
           if (drive.VolumeLabel == "TESTLABEL") Console.WriteLine("USB Stick is plugged in");
        }
    }
}

You can hook to (USB) Events using the ManagementEventWatcher . 您可以使用ManagementEventWatcher挂钩(USB)事件。

Working example for LinqPad paraphrasing this neat answer which uses the Win32_DeviceChangeEvent : LinqPad的工作示例解释了这个使用Win32_DeviceChangeEvent 简洁答案

// using System.Management;
// reference System.Management.dll
void Main()
{    
    using(var control = new USBControl()){
        Console.ReadLine();//block - depends on usage in a Windows (NT) Service, WinForms/Console/Xaml-App, library
    }
}

class USBControl : IDisposable
    {
        // used for monitoring plugging and unplugging of USB devices.
        private ManagementEventWatcher watcherAttach;
        private ManagementEventWatcher watcherDetach;

        public USBControl()
        {
            // Add USB plugged event watching
            watcherAttach = new ManagementEventWatcher();
            watcherAttach.EventArrived += Attaching;
            watcherAttach.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
            watcherAttach.Start();

            // Add USB unplugged event watching
            watcherDetach = new ManagementEventWatcher();
            watcherDetach.EventArrived += Detaching;
            watcherDetach.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3");
            watcherDetach.Start();
        }

        public void Dispose()
        {
            watcherAttach.Stop();
            watcherDetach.Stop();
            //you may want to yield or Thread.Sleep
            watcherAttach.Dispose();
            watcherDetach.Dispose();
            //you may want to yield or Thread.Sleep
        }

        void Attaching(object sender, EventArrivedEventArgs e)
        {
            if(sender!=watcherAttach)return;
            e.Dump("Attaching");
        }

        void Detaching(object sender, EventArrivedEventArgs e)
        {
            if(sender!=watcherDetach)return;
            e.Dump("Detaching");
        }

        ~USBControl()
        {
            this.Dispose();// for ease of readability I left out the complete Dispose pattern
        }
    }

When attaching a USB-Stick I'll receive 7 attach (resp. detach) Events. 连接USB-Stick时,我将收到7个附加(分配)事件。 Customize the Attaching/Detaching methods as you like. 根据需要自定义附加/分离方法。 The blocking part is left to the reader, depending on his needs, with a Windows Service you wouldn't need to block at all. 阻止部分留给读者,根据他的需要,使用您根本不需要阻止的Windows服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM