c# usb detection

青春壹個敷衍的年華 提交于 2019-12-05 11:29:34

From what I've seen, that's normal. I run into exactly the same issue here.

Two things you can do - set a var for DateTime.Now and then check on the next arrival to see if time difference between the arrivals is less than x seconds from the last time there was an event (basically store the time from when you last handled an arrival)

or

You can store the list of drives and if the event handles the same device as you already have, then you ignore it.

But yes, because USB devices often present themselves to the system as multiple devices, it tends to send multiple device insertions.

Another thing I've used to get around this is using WMI's events, with a watcher to detect logical storage events (__InstanceCreation with a target of Win32_LogicalDisk)

    private void startMonitor()
    {
        while (serviceStarted)
        {
            ManagementEventWatcher watcher = new ManagementEventWatcher();

            WqlEventQuery query = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_LogicalDisk'");

            watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
            watcher.Query = query;
            watcher.Start();
            watcher.WaitForNextEvent();
        }
        Thread.CurrentThread.Abort();
    }

With the EventArrived handler of...

    private void watcher_EventArrived(object obj, EventArrivedEventArgs e)
    {
            var newEvent = e.NewEvent;

            ManagementBaseObject targetInstance = (ManagementBaseObject)newEvent.GetPropertyValue("TargetInstance");

            string drivename = targetInstance.GetPropertyValue("Name").ToString();

Drivename ends up actually being the drive letter, such as D: or whatever...

Downside of that is the app needs to run with the correct privileges for the local WMI scope and it's slightly more intensive than passively handling window messages.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!