C#:EZUSB实战(三)监视U盘插拔

同系列文章:

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

EZUSB核心源代码出售:

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

演示程序功能说明:

自动实现对USB HUB设备和USB STORAGE设备的插拔监控,并触发插拔事件。支持USB HUB设备过滤功能,可以只监视特定VID和PID的USB HUB设备。

演示程序下载:

EZUSBDemo.zip

演示程序界面:

源代码:
MainWindow.xaml

<Window x:Class="Splash.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Splash"
        mc:Ignorable="d"
        Title="屎壳郎U盘监视器 By 秦建辉 2017年02月08日" Height="600" Width="800" Icon="scarab.ico" WindowStartupLocation="CenterScreen" WindowState="Maximized" ResizeMode="CanMinimize" Loaded="Window_Loaded" FontSize="16" Closing="Window_Closing">
    <Grid x:Name="grid">
        <Grid.RowDefinitions>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <StackPanel Name="stackPanelMain" Grid.Row="0" Orientation="Vertical" Background="SteelBlue" />
    </Grid>
</Window>

MainWindow.xaml.cs

/* ----------------------------------------------------------
 * 文件名称:MainWindow.xaml.cs
 * 
 * 作者:秦建辉
 * 
 * 微信:splashcn
 * 
 * 博客:http://www.firstsolver.com/wordpress/
 * 
 * 开发环境:
 *      Visual Studio V2015
 *      .NET Framework 4 Client Profile
 *      
 * 版本历史:
 *      V1.0	2017年02月08日
 *              基于EZUSB实现U盘插拔监视
 * ------------------------------------------------------------ */
using Com.FirstSolver.Splash;
using Com.FirstSolver.USB;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace Splash
{
    /// <summary>
    /// 屎壳郎U盘监视器
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// U盘监视器
        /// </summary>
        private EZUSBSTOR Scarab = null;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                // 在UsbScarab.xml中定义好要监视的Usb Hub设备的Vid、Pid
                Scarab = new EZUSBSTOR();
                Scarab.Initialize("UsbScarab.xml", new TimeSpan(0, 0, 3));

                // 添加USB HUB界面元素
                foreach (KeyValuePair<string, UsbHubNodeValue> hub in Scarab.UsbHubDictionary)
                {
                    AddUsbHubElement(hub);
                }

                // U盘插入事件处理器
                Scarab.OnUsbStorageCreationEventHandler += UsbStorageCreationEventHandler;

                // U盘移除事件处理器
                Scarab.OnUsbStorageDeletionEventHandler += UsbStorageDeletionEventHandler;

                // USB HUB插入事件处理器
                Scarab.OnUsbHubCreationEventHandler += UsbHubCreationEventHandler;

                // USB HUB移除事件处理器
                Scarab.OnUsbHubDeletionEventHandler += UsbHubDeletionEventHandler;
            }
            catch
            {
                MessageBoxPlus.Show(this, "U盘监视器初始化失败!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        // 添加USB HUB界面元素
        private void AddUsbHubElement(KeyValuePair<string, UsbHubNodeValue> hub)
        {   // 跨线程访问
            this.Dispatcher.Invoke(new Action(() => {
                SortedDictionary<int, UserControlUsbStor> sd = new SortedDictionary<int, UserControlUsbStor>();

                WrapPanel wp = new WrapPanel();
                wp.Orientation = Orientation.Horizontal;
                for (int i = 1; i <= hub.Value.NumberOfPorts; i++)
                {
                    UserControlUsbStor u = new UserControlUsbStor(i);
                    u.Width = 320;
                    u.Margin = new Thickness(8);

                    wp.Children.Add(u);
                    sd.Add(i, u);
                }

                GroupBox gb = new GroupBox();
                gb.Header = hub.Key;
                gb.Content = wp;
                gb.Margin = new Thickness(8);
                gb.Tag = sd;

                stackPanelMain.Children.Add(gb);
            }));
        }

        // U盘插入事件处理
        public void UsbStorageCreationEventHandler(object sender, UsbStorageEventArgs e)
        {   // 跨线程访问
            this.Dispatcher.Invoke(new Action(() => {
                foreach (UIElement Element in stackPanelMain.Children)
                {
                    if (Element is GroupBox)
                    {
                        GroupBox gb = (GroupBox)Element;
                        if (string.Equals(e.NodeValue.UsbHubDevID, gb.Header.ToString()))
                        {
                            UserControlUsbStor stor = ((SortedDictionary<int, UserControlUsbStor>)gb.Tag)[e.NodeValue.ConnectionIndex];
                            stor.Set(e.PNPDeviceID, e.NodeValue);
                            stor.Status = 2;    // 设置为空闲中
                        }
                    }
                }
            }));
        }

        // U盘移除事件处理
        public void UsbStorageDeletionEventHandler(object sender, UsbStorageEventArgs e)
        {   // 跨线程访问
            this.Dispatcher.Invoke(new Action(() => {
                foreach (UIElement Element in stackPanelMain.Children)
                {
                    if (Element is GroupBox)
                    {
                        GroupBox gb = (GroupBox)Element;
                        if (string.Equals(e.NodeValue.UsbHubDevID, gb.Header.ToString()))
                        {
                            ((SortedDictionary<int, UserControlUsbStor>)gb.Tag)[e.NodeValue.ConnectionIndex].Reset();
                        }
                    }
                }
            }));
        }

        // USB HUB插入事件处理
        public void UsbHubCreationEventHandler(object sender, UsbHubEventArgs e)
        {
            AddUsbHubElement(new KeyValuePair<string, UsbHubNodeValue>(e.PNPDeviceID, e.NodeValue));
        }

        // USB HUB移除事件处理
        public void UsbHubDeletionEventHandler(object sender, UsbHubEventArgs e)
        {   // 跨线程访问
            this.Dispatcher.Invoke(new Action(() => {
                foreach (UIElement Element in stackPanelMain.Children)
                {
                    if (Element is GroupBox)
                    {
                        GroupBox gb = (GroupBox)Element;
                        if (string.Equals(e.PNPDeviceID, gb.Header.ToString()))
                        {
                            stackPanelMain.Children.Remove(Element);
                        }
                    }
                }
            }));
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {   // 释放资源
            if (Scarab != null) Scarab.Dispose();
        }
    }
}

Comments are closed.