2010-10-25 68 views
4

我試圖監控驅動器本地PC。我對兩個事件感興趣:連接驅動器(USB驅動器,CD-ROM,網絡驅動器等)並斷開連接。我使用ManagementOperationObserver寫了一個概念的快速證明,它部分工作。現在(下面的代碼),我正在得到各種事件。當驅動器連接並斷開連接時,我只想獲取事件。有沒有辦法在Wql查詢中指定這個?使用WMI監控驅動器

謝謝!

private void button2_Click(object sender, EventArgs e) 
    { 
     t = new Thread(new ParameterizedThreadStart(o => 
     { 
      WqlEventQuery q; 
      ManagementOperationObserver observer = new ManagementOperationObserver(); 

      ManagementScope scope = new ManagementScope("root\\CIMV2"); 
      scope.Options.EnablePrivileges = true; 

      q = new WqlEventQuery(); 
      q.EventClassName = "__InstanceOperationEvent"; 
      q.WithinInterval = new TimeSpan(0, 0, 3); 
      q.Condition = @"TargetInstance ISA 'Win32_LogicalDisk' "; 
      w = new ManagementEventWatcher(scope, q); 

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

     t.Start(); 
    } 

    void w_EventArrived(object sender, EventArrivedEventArgs e) 
    { 
     //Get the Event object and display its properties (all) 
     foreach (PropertyData pd in e.NewEvent.Properties) 
     { 
      ManagementBaseObject mbo = null; 
      if ((mbo = pd.Value as ManagementBaseObject) != null) 
      { 
       this.listBox1.BeginInvoke(new Action(() => listBox1.Items.Add("--------------Properties------------------"))); 
       foreach (PropertyData prop in mbo.Properties) 
        this.listBox1.BeginInvoke(new Action<PropertyData>(p => listBox1.Items.Add(p.Name + " - " + p.Value)), prop); 
      } 
     } 
    } 
+0

快速評論:您不需要使用ParameterizedThreadStart,因爲您沒有使用該參數。只需使用ThreadStart。 – 2010-10-25 21:48:20

回答

5

你快到了。要區分連接到機器的驅動器和正在移除的驅動器,您需要檢查e.NewEvent是否分別是__InstanceCreationEvent__InstanceDeletionEvent的實例。沿着這些路線的東西:

ManagementBaseObject baseObject = (ManagementBaseObject) e.NewEvent; 

if (baseObject.ClassPath.ClassName.Equals("__InstanceCreationEvent")) 
    Console.WriteLine("A drive was connected"); 
else if (baseObject.ClassPath.ClassName.Equals("__InstanceDeletionEvent")) 
    Console.WriteLine("A drive was removed"); 

此外,您還可以通過TargetInstance財產獲得的Win32_LogicalDisk實例。

ManagementBaseObject logicalDisk = 
       (ManagementBaseObject) e.NewEvent["TargetInstance"]; 

Console.WriteLine("Drive type is {0}", 
        logicalDisk.Properties["DriveType"].Value);