繁体   English   中英

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

[英]How do I detect when a removable disk is inserted using C#?

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

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

试一试......

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");

        }
    }

}

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

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

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

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

自动播放版本2是Windows XP中的一项功能,它将扫描可移动媒体的前四个级别,当它到达时,查找媒体内容类型(音乐,图形或视频)。 应用程序的注册是基于内容类型完成的。 当可移动媒体到达时,Windows XP通过评估内容并将其与该内容的注册处理程序进行比较来确定要执行的操作。

还提供详细的MSDN文章

暂无
暂无

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

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