2010-05-14 64 views
1

我試圖在有人插入USB設備時啓動事件。目前,我只是簡單地將一些東西打印到控制檯上(在成品中,它將啓動一個應用程序)。使用WMI在Windows上插入USB設備時打開我的應用程序

此代碼是非常鬆散改編自:https://serverfault.com/questions/115496/use-wmi-to-detect-a-usb-drive-was-connected-regardless-of-whether-it-was-mounted

有兩個問題: 1)我需要通過參數來動態管理範圍,因爲這將被安裝在計算機上我不使用或他的名字我不知道。 2)當我調用w.Start()時,我得到一個無效的命名空間異常。

任何想法我做錯了什麼?

static ManagementEventWatcher w=null; 
static void Main(string[] args) 
    { 
     AddInstUSBHandler(); 
     for(;;); 
    } 

public static void USBRemoved(object sneder, EventArgs e) 
    { 
     Console.WriteLine("A USB device inserted"); 
    } 


static void AddInstUSBHandler() 
    { 
     WqlEventQuery q; 
     ManagementScope scope = new ManagementScope("HQ\\DEV1"); 
     scope.Options.EnablePrivileges=true; 

      q=new WqlEventQuery(); 
      q.EventClassName+="_InstanceCreationEvent"; 
      q.WithinInterval=new TimeSpan(0,0,3); 
      [email protected]"TargetInstance ISA 'Win32_USBControllerdevice'"; 
      w=new ManagementEventWatcher(scope,q); 
      w.EventArrived+=new EventArrivedEventHandler(USBRemoved); 
      w.Start(); 
    } 

回答

1

這行不正確 - > 「HQ \ DEV1」

//ManagementScope scope = new ManagementScope("HQ\\DEV1"); 

按照ManagementScope Class

// Make a connection to a remote computer. 
    // Replace the "FullComputerName" section of the 
    // string "\\\\FullComputerName\\root\\cimv2" with 
    // the full computer name or IP address of the 
    // remote computer. 
    ManagementScope scope = 
     new ManagementScope(
     "\\\\FullComputerName\\root\\cimv2"); 
+0

我加入了完整計算機名稱 - 然後得到 「無效的類」。如果將其更改爲\\\\ HQ \\ DEV1 \\ root \\ cimv2(它不是完整的計算機名稱,但是域中的路徑),則會顯示「訪問被拒絕」。那是因爲我不是我盒子上的管理員? – rsteckly 2010-05-14 21:46:20

+0

我會這麼說。我一直有類似的問題。如果您轉到計算機管理 - >服務和應用程序 - > WMI控制,則您或您的系統adim可以設置權限。我已經在Windows 7和XP上完成了這一點,但我只能訪問XP。 – hfitzwater 2011-10-10 14:47:07

相關問題