簡體   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