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

时间:2008-11-07 04:24:05

标签: c# wpf windows

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

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

3 个答案:

答案 0 :(得分: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");

        }
    }

}

答案 1 :(得分:9)

使用WMI轮询比执行此操作简单得多 - 只需捕获WM_DEVICECHANGE:

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

答案 2 :(得分:1)

最简单的方法是创建一个自动播放处理程序:

http://www.codeproject.com/KB/system/AutoplayDemo.aspx

  

自动播放版本2是一项功能   Windows XP将扫描第一个   四个级别的可移动媒体,何时   它到了,寻找媒体内容   类型(音乐,图形或视频)。   申请注册已完成   在内容类型的基础上。当一个   可移动媒体到来,Windows XP   确定要执行的操作   评估内容和比较   它是注册处理程序的   内容。

也可以使用detailed MSDN article

相关问题