【1】涉及的知识点

1) windows消息处理函数

1
protected override void WndProc(ref Message m)

捕获Message的系统硬件改变发出的系统消息

2) 硬件信息类

1
DriveInfo

【2】核心函数

消息常量:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/// <summary>
/// windows消息常量
/// </summary>
class CWndProMsgConst
{
    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_DEVICETYPEHANGED = 0x0007;
    public const int DBT_QUERYCHANGSPECIFIC = 0x8005;
    public const int DBT_DEVNODES_CECONFIG = 0x0017;
    public const int DBT_USERDEFINED = 0xFFFF;
}   

扫描函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/// <summary>
/// 扫描U口设备
/// </summary>
private void ScanUSBDisk()
{
    _usbdiskList.Clear();
    DriveInfo[] drives = DriveInfo.GetDrives();
 
    foreach (DriveInfo drive in drives)
    {
        if ((drive.DriveType == DriveType.Removable) && !drive.Name.Substring(0, 1).Equals("A"))
        {
            try
            {
                _usbdiskList.Add(drive.Name);
            }
            catch
            {
                MessageBox.Show("当前盘不能正确识别,请重新尝试!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}

消息处理函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public void FillData(Form form, Message m, ListBox listbox)
{
    _listbox = listbox;
    _form    = form;
 
    try
    {
        if (m.Msg == CWndProMsgConst.WM_DEVICECHANGE) // 系统硬件改变发出的系统消息
        {
            switch (m.WParam.ToInt32())
            {
                case CWndProMsgConst.WM_DEVICECHANGE:
                    break;
                //设备检测结束,并且可以使用
                case CWndProMsgConst.DBT_DEVICEARRIVAL:
                    {
                        ScanUSBDisk();
                        _listbox.Items.Clear();
                        foreach (string str in _usbdiskList)
                        {
                            _listbox.Items.Add(str);
                        }                               
                    }
                    break;
                // 设备卸载或者拔出
                case CWndProMsgConst.DBT_DEVICEREMOVECOMPLETE:
                    {
                        ScanUSBDisk();
                        _listbox.Items.Clear();
                        foreach (string str in _usbdiskList)
                        {
                            _listbox.Items.Add(str);
                        }
                    }                          
                    break;
                default:
                    break;
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("当前盘不能正确识别,请重新尝试!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}          

完整的CS封装文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
 
namespace USBMonitor
{
    /// <summary>
    /// USB插拔监控类
    /// </summary>
    public class CUSBMonitor
    {
        private delegate void SetTextCallback(string s);
        private IList<string> _usbdiskList = new List<string>();
        private ListBox _listbox = null;
        private Form    _form  = null;
 
        public CUSBMonitor()
        {
            System.Timers.Timer timer = new System.Timers.Timer(1000);
            timer.Enabled = true;
 
            // 达到间隔时发生
            timer.Elapsed += new System.Timers.ElapsedEventHandler(TimerList);
            timer.AutoReset = false; // 仅在间隔第一次结束后引发一次         
        }
 
        public void FillData(Form form, Message m, ListBox listbox)
        {
            _listbox = listbox;
            _form    = form;
 
            try
            {
                if (m.Msg == CWndProMsgConst.WM_DEVICECHANGE) // 系统硬件改变发出的系统消息
                {
                    switch (m.WParam.ToInt32())
                    {
                        case CWndProMsgConst.WM_DEVICECHANGE:
                            break;
                        //设备检测结束,并且可以使用
                        case CWndProMsgConst.DBT_DEVICEARRIVAL:
                            {
                                ScanUSBDisk();
                                _listbox.Items.Clear();
                                foreach (string str in _usbdiskList)
                                {
                                    _listbox.Items.Add(str);
                                }                               
                            }
                            break;
                        // 设备卸载或者拔出
                        case CWndProMsgConst.DBT_DEVICEREMOVECOMPLETE:
                            {
                                ScanUSBDisk();
                                _listbox.Items.Clear();
                                foreach (string str in _usbdiskList)
                                {
                                    _listbox.Items.Add(str);
                                }
                            }                          
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("当前盘不能正确识别,请重新尝试!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }          
 
        /// <summary>
        /// 设置USB列表
        /// </summary>
        void TimerList(object sender, System.Timers.ElapsedEventArgs e)
        {
            ScanUSBDisk();
            foreach (string str in _usbdiskList)
            {
                SetText(str);
            }
        }
 
        /// <summary>
        /// 扫描U口设备
        /// </summary>
        private void ScanUSBDisk()
        {
            _usbdiskList.Clear();
            DriveInfo[] drives = DriveInfo.GetDrives();
 
            foreach (DriveInfo drive in drives)
            {
                if ((drive.DriveType == DriveType.Removable) && !drive.Name.Substring(0, 1).Equals("A"))
                {
                    try
                    {
                        _usbdiskList.Add(drive.Name);
                    }
                    catch
                    {
                        MessageBox.Show("当前盘不能正确识别,请重新尝试!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
        }
 
        /// <summary>
        /// 设置List列表
        /// </summary>
        /// <param name="text">名称
        public void SetText(string text)
        {
            if (_listbox == null)
                return;
 
            if (this._listbox.InvokeRequired) // 调用方位于创建控件所在的线程以外的线程中
            {
                if (_listbox.Items.Contains(text))
                    return;
 
                SetTextCallback d = new SetTextCallback(SetText);
                _form.Invoke(d, new object[] { text });
            }
            else
            {
                if (_listbox.Items.Contains(text))
                    return;
 
                this._listbox.Items.Add(text);
            }
        }
    }
 
    /// <summary>
    /// windows消息常量
    /// </summary>
    class CWndProMsgConst
    {
        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_DEVICETYPEHANGED = 0x0007;
        public const int DBT_QUERYCHANGSPECIFIC = 0x8005;
        public const int DBT_DEVNODES_CECONFIG = 0x0017;
        public const int DBT_USERDEFINED = 0xFFFF;
    }   
}
</string></string>

测试窗体(重写消息函数):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace USBMonitor
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }
 
        CUSBMonitor usbMonitor = new CUSBMonitor();
 
        protected override void WndProc(ref Message m)
        {
            usbMonitor.FillData(this, m, _listBox);
 
            base.WndProc(ref m);
        }
    }
}

C#.NET U盘插拔监控的更多相关文章

  1. 如何在Windows服务程序中添加U盘插拔的消息

    研究了下这个问题,主要要在一般的windows服务程序中修改两个地方: 一.调用RegisterServiceCtrlHandlerEx VOID WINAPI SvcMain( DWORD dwAr ...

  2. android6.0 外部存储设备插拔广播以及获取路径(U盘)【转】

    本文转载自:https://blog.csdn.net/zhouchengxi/article/details/53982222 这里我将U盘作为例子来说明解析. android4.1版本时U盘插拔时 ...

  3. QTC++监控USB插拔

    #if defined(Q_OS_WIN) #include <qt_windows.h> #include <QtCore/qglobal.h> #include <d ...

  4. ARM上的linux如何实现无线网卡的冷插拔和热插拔

    ARM上的linux如何实现无线网卡的冷插拔和热插拔 fulinux 凌云实验室 1. 冷插拔 如果在系统上电之前就将RT2070/RT3070芯片的无线网卡(以下简称wlan)插上,即冷插拔.我们通 ...

  5. 增加 addDataScheme("file") 才能收到SD卡插拔事件的原因分析 -- 浅析android事件过滤策略

    http://blog.csdn.net/silenceburn/article/details/6083375 =========================================== ...

  6. 某天U盘插在笔记本打不开了,是U盘坏了还是电脑的问题?

    五六月份忙着毕业设计与毕业论文,U盘在这个时候就是大功臣啦! 然而打印完最终版本论文上交后,再次把U盘插在自己的笔记本上读取失败了... 只有一个空白的图标,打不开,也无法格式化. 试着删除,拔了又插 ...

  7. Oracle可插拔数据库的jdbc连接串写法

    我在服务器上部署某个第三方系统的数据库的时候,服务器数据库版本为oracle 12c.我采用的方式是新建了一个实例.访问正常. 后来项目的负责人告诉我,oracle12C支持所谓的可插拔数据库.可插拔 ...

  8. 笔记本u盘插上不显示

    u盘突然拔出笔记本再次插入时不显示: 解决方法:我的电脑-设备管理器-其他设备(你的U盘驱动)-卸载 再重新插上去,即可显示

  9. kafka可插拔增强如何实现?

    导弹拦截,精准防御. 背景 拦截器:在不修改应用程序业务逻辑的情况下,一组基于事件的可插拔的逻辑处理链: 类比springMVC的拦截器: 这些都是通过配置拦截器,插入到应用程序中,实现可插拔的修改业 ...

随机推荐

  1. [转载+原创]Emgu CV on C# (六) —— Emgu CV on Canny边缘检测

    Canny边缘检测也是一种边缘检测方法,本文介绍了Canny边缘检测的函数及其使用方法,并利用emgucv方法将轮廓检测解算的结果与原文进行比较. 图像的边缘检测的原理是检测出图像中所有灰度值变化较大 ...

  2. linux 下安装 nginx

    安装nginx版本为1.7.5 一.下载nginx 官方地址:http://www.nginx.org/ 下载地址:http://nginx.org/download/ Nginx官网提供了三个类型的 ...

  3. POJ 1804

    /* *由此题发现规律 就是冒泡排序的交换次数等于这个数列的逆序对 的对数! */ #include<iostream> #include<stdio.h> #include& ...

  4. C# DataTable转换成DataRow

    linq中的cast<T>()及OfType<T>() DataTable dt=...........//获取从数据库中取出的数据(假设只有一条记录) //Cast<T ...

  5. POJ1258Agri-Net

    http://poj.org/problem?id=1258 题意 : john当上了镇长,打算给每个农场都连接网络,需要用最小的成本连接其他所有农场,所以要找最少的纤维连在一起,任何两个农场之间的距 ...

  6. CSS中nth-child和nth-of-type的简单使用

    ele:nth-child是查找父元素下的子元素,包括子元素类型非ele的,当子元素类型不是ele时,则不会进行任何操作: ele:nth-of-type是查找父元素下的子元素类型为ele的元素,其是 ...

  7. Project Euler 81:Path sum: two ways 路径和:两个方向

    Path sum: two ways In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom ...

  8. 用JUnit4进行单元测试

    转载:http://tonl.iteye.com/blog/1948869 参考: http://thihy.iteye.com/blog/1771826 http://developer.51cto ...

  9. 卓京---java基础2

    2.数据类型 基本类型: 整型: byte字节型   8位(bit) -2^7~2^7-1(-128~127)  0000 0000 short短整型  16位 -2^15~2^15-1(-32768 ...

  10. 关于delphi Assigned

    1. 根据 Delphi 指令参考手册中 说明: Assigned 函式在参数不为 nil 时传回 True, 表示指针已经指到某个内存地址,这个内存地址可能是一个对象地首地址,也可能在函数或过程中, ...