如何使用C#检测何时插入可移动磁盘?

Dav*_*ell 16 c# windows wpf

我只关心Windows,所以没有必要进入关于Mono兼容性或类似的东西的esoterica.

我还应该补充一点,我正在编写的应用程序是WPF,System.Windows.Forms如果可能的话,我宁愿避免依赖它.

Jos*_*ola 16

试一试......

using System;
using System.Collections.Generic;
using System.Text;
using System.Management;

namespace WMITestConsolApplication
{

    class Program
    {

        static void Main(string[] args)
        {

            AddInsertUSBHandler();
            AddRemoveUSBHandler();
            while (true) {
            }

        }

        static ManagementEventWatcher w = null;

        static void AddRemoveUSBHandler()
        {

            WqlEventQuery q;
            ManagementScope scope = new ManagementScope("root\\CIMV2");
            scope.Options.EnablePrivileges = true;

            try {

                q = new WqlEventQuery();
                q.EventClassName = "__InstanceDeletionEvent";
                q.WithinInterval = new TimeSpan(0, 0, 3);
                q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'";
                w = new ManagementEventWatcher(scope, q);
                w.EventArrived += USBRemoved;

                w.Start();
            }
            catch (Exception e) {


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

                }
            }

        }

        static void AddInsertUSBHandler()
        {

            WqlEventQuery q;
            ManagementScope scope = new ManagementScope("root\\CIMV2");
            scope.Options.EnablePrivileges = true;

            try {

                q = new WqlEventQuery();
                q.EventClassName = "__InstanceCreationEvent";
                q.WithinInterval = new TimeSpan(0, 0, 3);
                q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'";
                w = new ManagementEventWatcher(scope, q);
                w.EventArrived += USBInserted;

                w.Start();
            }
            catch (Exception e) {

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

                }
            }

        }

        static void USBInserted(object sender, EventArgs e)
        {

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

        }

        static void USBRemoved(object sender, EventArgs e)
        {

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

        }
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 在我的系统上,当我插入时,我得到4个插入和4个删除事件,然后拉出我的笔式驱动器... (2认同)
  • 在我的系统上,我得到两个插入事件和两个删除事件.似乎无法区分它们.有任何想法吗? (2认同)

Ana*_*tts 9

与使用WMI轮询相比,执行此操作的方法要少得多 - 只需捕获WM_DEVICECHANGE:

http://msdn.microsoft.com/en-us/library/aa363215.aspx