2011-01-25 40 views
1

我用下面的代碼,當它連接到電腦上檢測到USB設備:檢測iPhone在C#中使用WMI

private ManagementEventWatcher m_watcher; 
try 
    { 
     string queryString = 
      "SELECT * " + 
      " FROM __InstanceCreationEvent " + 
      " WITHIN " + pollingInterval + 
      " WHERE TargetInstance ISA 'Win32_USBHub'"; 

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

     m_watcher = new ManagementEventWatcher(scope, processQuery); 
     m_watcher.EventArrived += new System.Management.EventArrivedEventHandler(EventArrived); 
     m_watcher.Start(); 
    } 

private void EventArrived(object sender, EventArrivedEventArgs e) 
{ 
    var instance = ((PropertyData)(e.NewEvent.Properties["TargetInstance"])); 
    var obj = (ManagementBaseObject)instance.Value; 
    var args = new InsertEventArgs(); 

    var description = (string)obj.Properties["Description"].Value; 
    var deviceId = (string) obj.Properties["DeviceID"].Value; 
    var status = (string) obj.Properties["Status"].Value; 

這正常工作當我將USB密鑰和一個三星手機。當我連接iPhone時,EventArrived功能從未被擊中。我使用了錯誤的事件嗎?我究竟做錯了什麼?

+0

任何這方面的運氣? – kakopappa 2011-04-25 08:24:23

回答

1

試試這個代碼:

var queryStr = "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_PnPEntity'"; 

var watcher = new ManagementEventWatcher(queryStr); 
watcher.EventArrived += DeviceChangeEventReceived; 
watcher.Start(); 

事件處理程序:

private static void DeviceChangeEventReceived(object sender, EventArrivedEventArgs e) 
{ 
    var instance = ((PropertyData)(e.NewEvent.Properties["TargetInstance"])); 
    var obj = (ManagementBaseObject)instance.Value; 

    var description = (string)obj.Properties["Description"].Value; 
    var deviceId = (string)obj.Properties["DeviceID"].Value; 
    var status = (string)obj.Properties["Status"].Value; 
}