使用WMI监控驱动器

4

我正在尝试监控本地计算机的驱动器。我对两个事件感兴趣:当驱动器连接(USB驱动器、CD-ROM、网络驱动器等)和断开连接时。我使用ManagementOperationObserver编写了一个快速的概念验证,它部分工作。现在(使用下面的代码),我正在获取各种各样的事件。我想只获取驱动器连接和断开连接的事件。有没有办法在Wql查询中指定这一点?

谢谢!

    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);
            }
        }
    }

快速评论:由于您没有使用参数,因此不需要使用ParameterizedThreadStart。只需使用ThreadStart即可。 - OJ.
1个回答

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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接