C#监控usb设备插拔--已经测试

发布时间 2023-04-21 15:44:04作者: 龙骑科技

WindowsFormsApp---USBDevicefind监听usb插拔

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp___USBDevicefind
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public const int WM_DEVICECHANGE = 0x219;               //U盘插入后,OS的底层会自动检测到,然后向应用程序发送“硬件设备状态改变“的消息
        public const int DBT_DEVICEARRIVAL = 0x8000;            //就是用来表示U盘可用的。一个设备或媒体已被插入一块,现在可用。
        public const int DBT_CONFIGCHANGECANCELED = 0x0019;     //要求更改当前的配置(或取消停靠码头)已被取消。
        public const int DBT_CONFIGCHANGED = 0x0018;            //当前的配置发生了变化,由于码头或取消固定。
        public const int DBT_CUSTOMEVENT = 0x8006;              //自定义的事件发生。 的Windows NT 4.0和Windows 95:此值不支持。
        public const int DBT_DEVICEQUERYREMOVE = 0x8001;        //审批要求删除一个设备或媒体作品。任何应用程序也不能否认这一要求,并取消删除。
        public const int DBT_DEVICEQUERYREMOVEFAILED = 0x8002;  //请求删除一个设备或媒体片已被取消。
        public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;     //一个设备或媒体片已被删除。
        public const int DBT_DEVICEREMOVEPENDING = 0x8003;      //一个设备或媒体一块即将被删除。不能否认的。
        public const int DBT_DEVICETYPESPECIFIC = 0x8005;       //一个设备特定事件发生。
        public const int DBT_DEVNODES_CHANGED = 0x0007;         //一种设备已被添加到或从系统中删除。
        public const int DBT_QUERYCHANGECONFIG = 0x0017;        //许可是要求改变目前的配置(码头或取消固定)。
        public const int DBT_USERDEFINED = 0xFFFF;              //此消息的含义是用户定义的
        public const int DBT_DEVTYP_VOLUME = 0x00000002;

        /// <summary>
        /// 处理windows 消息
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            try
            {
                if (m.Msg == WM_DEVICECHANGE)
                {
                    switch (m.WParam.ToInt32())
                    {
                        case WM_DEVICECHANGE:
                            //MessageBox.Show("判断检测USB插入电脑");
                            break;
                        case DBT_DEVICEARRIVAL:
                            MessageBox.Show("判断检测USB插入电脑");
                            DriveInfo[] s = DriveInfo.GetDrives();
                            foreach (DriveInfo drive in s)
                            {
                                if (drive.DriveType == DriveType.Removable)
                                {
                                    break;
                                }
                            }
                            break;
                        case DBT_CONFIGCHANGECANCELED:
                            break;
                        case DBT_CONFIGCHANGED:
                            break;
                        case DBT_CUSTOMEVENT:
                            break;
                        case DBT_DEVICEQUERYREMOVE:
                            break;
                        case DBT_DEVICEQUERYREMOVEFAILED:
                            break;
                        case DBT_DEVICEREMOVECOMPLETE:
                            MessageBox.Show("判断检测USB拔出电脑");
                            break;
                        case DBT_DEVICEREMOVEPENDING:
                            break;
                        case DBT_DEVICETYPESPECIFIC:
                            break;
                        case DBT_DEVNODES_CHANGED:
                            break;
                        case DBT_QUERYCHANGECONFIG:
                            break;
                        case DBT_USERDEFINED:
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            base.WndProc(ref m);
        }
    }
}

效果:

 

ConsoleApp---TestUSBDeviceFind监听usb插拔

代码:

using System;
using System.Collections.Generic;
using System.Management;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApp___TestUSBDeviceFind
{
    internal class Program
    {
       

        static void Main(string[] args)
        {
            try
            {
                //查询所有设备的插拔事件
                #region 第一种查询方法
                //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);
                        //hid 10进制 pid=57346,vid=1137 十六进制 pid=0xE002,vid=0x0471
                        //adb 10进制 pid=17,vid=8711 十六进制 pid=0x011,vid=0x2207
                        //UsbHelper.WhoUsbDevice(57346, 1137);
                    }

                    //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();
                #endregion

                #region 第二种查询方法
                //// Full query string specified to the constructor
                //WqlEventQuery q = new WqlEventQuery("SELECT * FROM Win32_ComputerShutdownEvent");

                //// Only relevant event class name specified to the constructor
                //// Results in the same query as above.
                //WqlEventQuery query = new WqlEventQuery("Win32_ComputerShutdownEvent");

                //Console.WriteLine(query.QueryString);

                //ConnectionOptions connectionOptions = new ConnectionOptions();
                //connectionOptions.EnablePrivileges = true;//启用用户特权

                //ManagementScope managementScope = new ManagementScope("root\\CIMV2", connectionOptions);

                //WqlEventQuery wqlEventQuery = new WqlEventQuery();
                //wqlEventQuery.EventClassName = "Win32_DeviceChangeEvent";
                //wqlEventQuery.Condition = "EventType = 2 or EventType = 3";
                //wqlEventQuery.WithinInterval = TimeSpan.FromSeconds(1);

                //ManagementEventWatcher watcher = new ManagementEventWatcher(managementScope, wqlEventQuery);
                ////watcher.EventArrived += Watcher_EventArrived;
                //watcher.EventArrived += (sender, e) =>
                //{
                //    var txt = "";
                //    foreach (var p in e.NewEvent.Properties)
                //    {
                //        txt = "name " + p.Name + " val " + p.Value + "\r\n";
                //        Console.WriteLine(txt);
                //        DeviceManage.Instance.FindDevice();
                //    }
                //};
                //watcher.Start();

                #endregion

                Console.Read();
                //ServicesManager.Instance.StartServices();
                //Thread.CurrentThread.IsBackground = false;
                //Thread.Sleep(Timeout.Infinite);
            }
            catch (Exception e)
            {
                //logger.Error("Main", e);
            }
        }

        private static void Watcher_EventArrived(object sender, EventArrivedEventArgs e)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// C#检测pc光驱里是否插入了光盘的方法
        /// </summary>
        /// <param name="args"></param>
        static void Main2(string[] args)
        {
            ManagementEventWatcher w = null;
            WqlEventQuery q;
            ManagementOperationObserver observer = new ManagementOperationObserver();
            // Bind to local machine
            ConnectionOptions opt = new ConnectionOptions();
            opt.EnablePrivileges = true;//sets required privilege启动用户特权
            ManagementScope scope = new ManagementScope("root\\CIMV2", opt);
            try
            {
                q = new WqlEventQuery();
                q.EventClassName = "__InstanceModificationEvent";
                q.WithinInterval = new TimeSpan(0, 0, 1);
                // DriveType - 5: CDROM
                q.Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5";
                w = new ManagementEventWatcher(scope, q);
                // register async. event handler
                w.EventArrived += new EventArrivedEventHandler(CDREventArrived);
                w.Start();
                // Do something usefull,block thread for testing
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                w.Stop();
            }
        }

        // Dump all properties
        public static void CDREventArrived(object sender, EventArrivedEventArgs e)
        {
            // Get the Event object and display it
            PropertyData pd = e.NewEvent.Properties["TargetInstance"];
            if (pd != null)
            {
                ManagementBaseObject mbo = pd.Value as ManagementBaseObject;

                // if CD removed VolumeName == null
                if (mbo.Properties["VolumeName"].Value != null)
                {
                    Console.WriteLine("CD has been inserted");
                }
                else
                {
                    Console.WriteLine("CD has been ejected");
                }
            }
        }
    }

 

效果:

 

WPFApp---USBDevicefind监听usb插拔

代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPFApp___USBDevicefind
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private IntPtr _intPtr = new IntPtr();//当前窗口句柄
        public const int WM_DEVICECHANGE = 0x219;//Windows消息编号
        //public const int DBT_DEVICEARRIVAL = 0x8000;
        //public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
        public const int DBT_DEVNODES_CHANGED = 0x0007;

        //public const int WM_DEVICECHANGE = 0x219;
        public const int DBT_DEVICEARRIVAL = 0x8000;
        public const int DBT_CONFIGCHANGECANCELED = 0x0019;
        public const int DBT_CONFIGCHANGED = 0x0018;
        public const int DBT_CUSTOMEVENT = 0x8006;
        public const int DBT_DEVICEQUERYREMOVE = 0x8001;
        public const int DBT_DEVICEQUERYREMOVEFAILED = 0x8002;
        public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
        public const int DBT_DEVICEREMOVEPENDING = 0x8003;
        public const int DBT_DEVICETYPESPECIFIC = 0x8005;
        //public const int DBT_DEVNODES_CHANGED = 0x0007;
        public const int DBT_QUERYCHANGECONFIG = 0x0017;
        public const int DBT_USERDEFINED = 0xFFFF;

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            _intPtr = new WindowInteropHelper(this).Handle;
            HwndSource hwndSource = HwndSource.FromHwnd(_intPtr);
            // 添加处理程序
            if (hwndSource != null) hwndSource.AddHook(HwndSourceHook);
        }       

        /// <summary>
        /// 钩子函数
        /// </summary>
        /// <param name="hwnd"></param>
        /// <param name="msg"></param>
        /// <param name="wParam"></param>
        /// <param name="lParam"></param>
        /// <param name="handled"></param>
        /// <returns></returns>
        public IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == WM_DEVICECHANGE)
            {
                //switch (wParam.ToInt32())
                //{
                //    case DBT_DEVNODES_CHANGED: //已在系统中添加或删除设备。
                //        System.Diagnostics.Debug.WriteLine("HwndSourceHook触发FindDevice");
                //        //DeviceManage.Instance.FDevice();//自定义处理方法
                //        break;
                //    //case DBT_DEVICEARRIVAL://已插入设备或介质,现已可用。
                //    // MessageBox.Show("已插入设备或介质,现已可用。");
                //    // break;
                //    //case DBT_DEVICEREMOVECOMPLETE: //已删除设备或介质。
                //    // MessageBox.Show("已删除设备或介质。");
                //    // break;

                //    default:
                //        break;
                //}

                switch (wParam.ToInt32())
                {
                    case WM_DEVICECHANGE:
                        //MessageBox.Show("USB插入电脑---WM_DEVICECHANGE  改变");
                        break;
                    case DBT_DEVICEARRIVAL:
                        MessageBox.Show("USB插入电脑---DBT_DEVICEARRIVAL   到达");
                        //MessageBox.Show("判断检测USB插入电脑");
                        //DriveInfo[] s = DriveInfo.GetDrives();
                        //foreach (DriveInfo drive in s)
                        //{
                        //    if (drive.DriveType == DriveType.Removable)
                        //    {
                        //        MessageBox.Show("U盘已插入,盘符为:" + drive.Name.ToString());
                        //        break;
                        //    }
                        //}
                        break;
                    case DBT_CONFIGCHANGECANCELED:
                        break;
                    case DBT_CONFIGCHANGED:
                        break;
                    case DBT_CUSTOMEVENT:
                        break;
                    case DBT_DEVICEQUERYREMOVE:
                        break;
                    case DBT_DEVICEQUERYREMOVEFAILED:
                        break;
                    case DBT_DEVICEREMOVECOMPLETE:
                        MessageBox.Show("判断检测USB拔出电脑--DBT_DEVICEREMOVECOMPLETE");
                        //int devType = Marshal.ReadInt32(m.LParam, 4);
                        //if (devType == DBT_DEVTYP_VOLUME)
                        //{
                        //    DEV_BROADCAST_VOLUME vol;
                        //    vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
                        //    string ID = vol.dbcv_unitmask.ToString("x");
                        //    MessageBox.Show("U盘已拔出,盘符为:" + IO(ID));
                        //}
                        break;
                    case DBT_DEVICEREMOVEPENDING:
                        break;
                    case DBT_DEVICETYPESPECIFIC:
                        break;
                    case DBT_DEVNODES_CHANGED:
                        break;
                    case DBT_QUERYCHANGECONFIG:
                        break;
                    case DBT_USERDEFINED:
                        break;
                    default:
                        break;
                }
            }
            return IntPtr.Zero;
        }
    }
}

效果: