C# 查询所有设备的插拔事件

     private void test()

        {

            //Win32_DeviceChangeEvent  Win32_VolumeChangeEvent

            ManagementEventWatcher watcher = new ManagementEventWatcher();

            WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent  WHERE EventType = 2 or EventType = 3");

 

            watcher.EventArrived += (s, e) =>

            {

                var txt = "";

               foreach( var p in e.NewEvent.Properties)

                {

                    txt += "name " + p.Name + " val " + p.Value + "\r\n";

 

                }

                Console.WriteLine(txt);

                //string driveName = e.NewEvent.Properties["DriveName"].Value.ToString();

                //EventType eventType = (EventType)(Convert.ToInt16(e.NewEvent.Properties["EventType"].Value));

 

                //string eventName = Enum.GetName(typeof(EventType), eventType);

 

                //Console.WriteLine("{0}: {1} {2}", DateTime.Now, driveName, eventName);

            };

 

            watcher.Query = query;

            watcher.Start();

            //Console.ReadKey();

        }

posted @ 2021-06-01 21:15  MaxBruce  阅读(422)  评论(0编辑  收藏  举报