2011年8月31日 星期三

[C#] 監控USB插拔 2

先前也寫過一篇 監控 USB 插拔的文章,見 http://kuomingwang.blogspot.com/2010/09/c-usb.html
但是那是監控已知的 USB 儲存設備,最近又有類似的需求,這算是另一種寫法。

//using System.Management;

ManagementEventWatcher mew = null;

         private void Form1_Load(object sender, EventArgs e)
        {
            mew = new ManagementEventWatcher("SELECT * FROM __InstanceOperationEvent WITHIN 10 WHERE TargetInstance ISA \"Win32_DiskDrive\"");
            mew.Start();
            mew.EventArrived += new EventArrivedEventHandler(mew_go);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            mew.Stop();
        }
        private void mew_go(object sender, System.Management.EventArrivedEventArgs e)
        {
            ManagementBaseObject newEvent = e.NewEvent, newEventTarget = (newEvent["TargetInstance"] as ManagementBaseObject);
            if (newEventTarget["InterfaceType"].ToString() == "USB")
            {
                switch (newEvent.ClassPath.ClassName)
                {
                    case "__InstanceCreationEvent":
                        Listbox_text_Update(listBox1, Convert.ToString(newEventTarget["Caption"])+" 裝置已插入");
                        break;
                    case "__InstanceDeletionEvent":
                        Listbox_text_Update(listBox1, Convert.ToString(newEventTarget["Caption"])+" 裝置已退出");
                        break;
                }
            }
        }
        public static void Listbox_text_Update(ListBox lbox, string s)
        {
            if (lbox.InvokeRequired)
            {
                lbox.BeginInvoke(new MethodInvoker(() => Listbox_text_Update(lbox, s)));
            }
            else
            {
                lbox.Items.Add(s);
            }
        }


沒有留言:

張貼留言