4

ローカルPCのドライブを監視しようとしています。ドライブが接続されているとき(USBドライブ、CD-ROM、ネットワークドライブなど)と切断されているときの2つのイベントに関心があります。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);
            }
        }
    }
4

1 に答える 1

5

あなたはほとんどそこにいます。マシンに接続されているドライブと取り外されているドライブを区別するには、それぞれ__InstanceCreationEventまたは__InstanceDeletionEvente.NewEventのインスタンスであるかどうかを確認する必要があります。これらの行に沿ったもの:

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);
于 2010-10-26T05:24:52.940 に答える