質問

ローカルPCのドライブを監視しようとしています。私は 2 つのイベントに興味があります:ドライブ (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);
            }
        }
    }
役に立ちましたか?

解決

もうすぐそこです。マシンに接続されているドライブと取り外されているドライブを区別するには、次のことを確認する必要があります。 e.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");

さらに、次の方法で Win32_LogicalDisk インスタンスを取得することもできます。 TargetInstance 財産。

ManagementBaseObject logicalDisk = 
               (ManagementBaseObject) e.NewEvent["TargetInstance"];

Console.WriteLine("Drive type is {0}", 
                  logicalDisk.Properties["DriveType"].Value);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top