C#:EZUSB实战(二)监视USB设备插拔

同系列文章:

  1. C#:EZUSB实战(一)USB设备浏览器
  2. C#:EZUSB实战(二)监视USB设备插拔
  3. C#:EZUSB实战(三)监视U盘插拔
  4. C#:EZUSB实战(四)启用和停用USB设备

EZUSB核心源代码出售:

sell
价格:壹仟圆人民币
微信:splashcn

演示程序功能说明:

自动监视USB设备的插拔,并显示插入的USB控制器和USB设备。

演示程序下载:

EZUSBDemo.zip

演示程序界面:

源代码:
Form1.cs

using Com.FirstSolver.USB;
using System;
using System.Management;
using System.Windows.Forms;

namespace Splash
{
    public partial class Form1 : Form
    {
        EZUSB Scarab = new EZUSB();
      
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Scarab.AddUsbEventWatcher(USBEventHandler, USBEventHandler, new TimeSpan(0, 0, 3));
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Scarab.RemoveUsbEventWatcher();
        }

        private void USBEventHandler(Object sender, EventArrivedEventArgs e)
        {
            if (e.NewEvent.ClassPath.ClassName == "__InstanceCreationEvent")
            {
                this.SetText("USB插入时间:" + DateTime.Now + "\r\n");
            }
            else if (e.NewEvent.ClassPath.ClassName == "__InstanceDeletionEvent") 
            {
                this.SetText("USB拔出时间:" + DateTime.Now + "\r\n");
            }

            UsbControllerDevice Device = EZUSB.WhoUsbControllerDevice(e);
            this.SetText("\tAntecedent:" + Device.Antecedent + "\r\n");
            this.SetText("\tDependent:" + Device.Dependent + "\r\n");
        }

        // 对 Windows 窗体控件进行线程安全调用
        private void SetText(string text)
        {   // 跨线程
            this.textBox1.BeginInvoke(new Action<string>((msg) =>
            {
                this.textBox1.AppendText(msg);
            }), text);
        }
    }
}

Comments are closed.