C#.NET U盤插拔監控


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM