使用WMI在Windows上插入USB设备时打开我的应用程序

时间:2010-05-14 20:20:45

标签: .net wmi

当有人插入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);
            q.Condition=@"TargetInstance ISA 'Win32_USBControllerdevice'";
            w=new ManagementEventWatcher(scope,q);
            w.EventArrived+=new EventArrivedEventHandler(USBRemoved);
            w.Start();
    }

1 个答案:

答案 0 :(得分: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");