2009-11-02 61 views
3

我正在開發一個項目,在該項目中,我需要能夠檢測何時插入或移除CD或USB驅動器。我發現一些本應該做這件事的源代碼,但是,當我插入或彈出CD時,似乎沒有任何事情發生。檢測彈出/插入可移除介質

有人可以請驗證來源是否正確,並且告訴我可能在這裏做錯了什麼?

public class MyWindow 
{ 
    ManagementEventWatcher w; 

    private void MyWindow_Loaded(object sender, RoutedEventArgs e) 
    { 
     WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 2"); 
     ConnectionOptions opt = new ConnectionOptions(); 
     opt.EnablePrivileges = true; 

     ManagementScope ms = new ManagementScope("root\\CIMV2", opt); 

     w = new ManagementEventWatcher(ms, query); 

     w.EventArrived += new EventArrivedEventHandler(w_EventArrived); 
     w.Start(); 
    } 

    private void w_EventArrived(object sender, EventArrivedEventArgs e) 
    { 
     PropertyData pd = e.NewEvent.Properties["TargetInstance"]; 
    } 
} 

當我在「PropertyData pd = ...」行設置一個斷點時,它在彈出/插入CD時不會被打到。由於我一點都沒有搞砸了,而且我在網上看到的所有例子都只是簡單地引用了相同的源代碼(只有很小的變化)

回答

4
using System.Management; 

public void networkDevice() 
{ 
    try 
    { 
     WqlEventQuery q = new WqlEventQuery(); 
     q.EventClassName = "__InstanceModificationEvent"; 
     q.WithinInterval = new TimeSpan(0, 0, 1); 
     q.Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5"; 

     ConnectionOptions opt = new ConnectionOptions(); 
     opt.EnablePrivileges = true; 
     opt.Authority = null; 
     opt.Authentication = AuthenticationLevel.Default; 
     //opt.Username = "Administrator"; 
     //opt.Password = ""; 
     ManagementScope scope = new ManagementScope("\\root\\CIMV2", opt); 

     ManagementEventWatcher watcher = new ManagementEventWatcher(scope, q); 
     watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); 
     watcher.Start(); 
    } 
    catch (ManagementException e) 
    { 
     Console.WriteLine(e.Message); 
    } 
} 

void watcher_EventArrived(object sender, EventArrivedEventArgs e) 
{ 
    ManagementBaseObject wmiDevice = (ManagementBaseObject)e.NewEvent["TargetInstance"]; 
    string driveName = (string)wmiDevice["DeviceID"]; 
    Console.WriteLine(driveName); 
    Console.WriteLine(wmiDevice.Properties["VolumeName"].Value); 
    Console.WriteLine((string)wmiDevice["Name"]); 
    if (wmiDevice.Properties["VolumeName"].Value != null) 
     Console.WriteLine("CD has been inserted"); 
    else 
     Console.WriteLine("CD has been ejected"); 
} 
+0

謝謝!這工作......我有點困惑,但爲什麼。我曾嘗試'... DriveType = 5',我看到的唯一的另一個區別是'root \\ CIMV2'之前的'\\'。 PEBCAK mebbe?我唯一要求的其他事情是,您的答案的格式化是固定的,因此它是可讀的。再次非常感謝! – 2009-11-18 18:02:18