我只關心Windows,所以不需要關於Mono兼容性或類似的東西進入奧祕。如何檢測何時使用C#插入可移動磁盤?
我還應該補充說,我正在編寫的應用程序是WPF,如果可能的話,我寧願避免依賴於System.Windows.Forms
。
我只關心Windows,所以不需要關於Mono兼容性或類似的東西進入奧祕。如何檢測何時使用C#插入可移動磁盤?
我還應該補充說,我正在編寫的應用程序是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");
}
}
}
最簡單的方法是創建一個自動播放處理程序:
http://www.codeproject.com/KB/system/AutoplayDemo.aspx
自動播放第2版是在 Windows XP的一個功能,將掃描第一 的4種可移動媒體,當 它到達,尋找媒體內容 類型(音樂,圖形或視頻)。 以內容類型爲基礎完成應用程序的註冊 。當 可移動媒體到達時,Windows XP 將確定要執行哪些操作,由 評估內容並將 與 內容的註冊處理程序進行比較。
A detailed MSDN article也可用。
這很酷,但我真的只是在尋找能夠在我的軟件運行時運行的東西。謝謝,不過。 – 2008-11-07 04:37:26
有這樣做比使用WMI查詢的麻煩較少的方法 - 只要捕捉WM_DEVICECHANGE:
我們是在談論一個USB港口? – 2008-11-07 04:26:04
USB驅動器將是可移動磁盤的一個例子,但Windows在處理事件時通常會將它們視爲光驅等。 – 2008-11-07 04:38:40