首页 > 编程语言 >C#监控usb设备插拔--已经测试

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

时间:2023-04-21 15:44:39浏览次数:39  
标签:插拔 usb C# System DBT break int using public

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;
        }
    }
}

效果:

 

标签:插拔,usb,C#,System,DBT,break,int,using,public
From: https://www.cnblogs.com/1175429393wljblog/p/17340609.html

相关文章

  • Approximation Theory and Method ch7
    ApproximationTheoryandMethodch7part1,part2,part3,ch7,命名乱了——致敬微软...asthesignof\(p(x)\).Itfollowsthat\(p^{*}\)isabestminimaxapproximationfrom\(\mathscr{A}\)to\(f\)ifthereisnofunction\(p\)in\(\mathscr{A}\)......
  • class(类)
    Class类学习学习类,以及类的有关方法,都基本到了这门语言语法的末尾章节了。类相较于其他知识点也是比较难理解的。如构造方法,类的继承,多态。1,类的构造方法1,构建类的方法的时候会自动执行2,构建类对象的传参会传递给构造方法3,构造方法可以给类的成员变量赋值写法......
  • Flink启动报错:/bin/config.sh: line 32: syntax error near unexpected token
    flink启动报错xxx@ssss:/xxx/flink-1.15.2/bin>shstart-cluster.sh/xxx/flink-1.15.2/bin/config.sh:line32:syntaxerrornearunexpectedtoken`<'/xxx/flink-1.15.2/bin/config.sh:line32:`done<<(find"$FLINK_LIB_DIR"!-ty......
  • Mac开发_NSTreeNode
    1、创建示例2、API说明@interfaceNSTreeNode:NSObject/***@brief创建一个包含指定modelObject对象的新树节点**@parammodelObject表示该节点的modelObject对象,可为nil*@return新创建的树节点**@discussion该方法创建了一......
  • 【汇智学堂】docker+springboot+mysql之二(springboot打包发送至Ubuntu dockermysql目
    IDEA:DockerfileContent:FROMjava:8VOLUME/tmpADDhellodocker-0.0.1-SNAPSHOT.jar/app.jarRUNsh-c'touch/app.jar'ENVJAVA_OPTS=""ENTRYPOINT["sh","-c","java$JAVA_OPTS-Djava.security.egd=file:/dev/.......
  • c++编译报错 error: parse error in template argument list
    [57%]BuildingCXXobjectdnet/CMakeFiles/dnet.dir/dconfig/dconfig_manager.cpp.oInfileincludedfrom/home/vi/git/dos/dnet/dconfig/dconfig_manager.cpp:1:/home/vi/git/dos/dnet/./dconfig/dconfig_manager.h:Inmemberfunction‘Tdnet::dconfig_manager::get_......
  • 【汇智学堂】docker+springboot+mysql之三(制作镜像并运行项目)
    Docker镜像仓库地址:https://hub.docker.com由于有墙,所以配置国内镜像,我们使用阿里云的镜像地址https://dev.aliyun.com/search…运行命令制作镜像:dockerbuild-t[容器名].注意:后面有个点,表示当前目录下//镜像名随意,注意最后有一个点发现没有mysql:查看所有发现msyql:5.......
  • 图像智能降噪工具:Topaz Photo AI for Mac v1.3.1
    TopazPhotoAI是一款适用于Mac的图像处理软件,它使用人工智能技术对照片进行编辑和优化。该软件提供了多种强大的功能,帮助用户轻松地改善图像质量,并实现自定义的效果。TopazPhotoAI支持多种文件格式,包括JPEG、TIFF、PNG、RAW等,并且能够自动检测并修复许多常见的问题,例如模糊、噪......
  • Swift CustomStringConvertible 协议的使用
    目录一、前言二、使用场景1.整型类型的枚举使用2.Class类型的使用一、前言先看一下Swift标准库中对CustomStringConvertible协议的定义publicprotocolCustomStringConvertible{///Atextualrepresentationofthisinstance.//////Callingthispropert......
  • vsCode添加插件方式
    vscode的几种安装插件方式1、联网正常的时候可以直接通过vsCode自带的工具直接搜索进行插件安装下载即可2、在有网络限制的时候,可以通过先下载的离线包进行安装插件vsCode下载离线包的地址:https://marketplace.visualstudio.com/vscode(到vscode官网,搜索想要的插件进行下......