冰楓論壇
標題:
[C#] 監控USB插拔
[打印本頁]
作者:
whitefox
時間:
2023-6-20 23:17
標題:
[C#] 監控USB插拔
方法一:
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 WM_MOUSE_DOUBLE_CHICK = 0x0203;
// USB 監控
protected override void WndProc(ref System.Windows.Forms.Message m)
{
try
{
if (m.Msg == WM_DEVICECHANGE)
{
switch (m.WParam.ToInt32())
{
case WM_DEVICECHANGE:
break;
case DBT_DEVICEARRIVAL://USB IN
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: //USB OUT
MessageBox.Show("You Flash ....Bye");
break;
case DBT_DEVICEREMOVEPENDING:
break;
case DBT_DEVICETYPESPECIFIC:
break;
case DBT_DEVNODES_CHANGED:
break;
case DBT_QUERYCHANGECONFIG:
break;
case DBT_USERDEFINED:
break;
default:
break;
}
}
// Mouse
if (m.Msg == WM_MOUSE_DOUBLE_CHICK)
{
MessageBox.Show("別在雙擊滑鼠左鍵了!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
base.WndProc(ref m);
}
複製代碼
方法二:
using System.Management;
ManagementEventWatcher mew = null;
private void Form1_Load(object sender, EventArgs e)
{
mew = new ManagementEventWatcher("SELECT * FROM __InstanceOperationEvent WITHIN 10 WHERE TargetInstance ISA \"Win32_DiskDrive\"");
mew.Start();
mew.EventArrived += new EventArrivedEventHandler(mew_go);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
mew.Stop();
}
private void mew_go(object sender, System.Management.EventArrivedEventArgs e)
{
ManagementBaseObject newEvent = e.NewEvent, newEventTarget = (newEvent["TargetInstance"] as ManagementBaseObject);
if (newEventTarget["InterfaceType"].ToString() == "USB")
{
switch (newEvent.ClassPath.ClassName)
{
case "__InstanceCreationEvent":
Listbox_text_Update(listBox1, Convert.ToString(newEventTarget["Caption"])+" 裝置已插入");
break;
case "__InstanceDeletionEvent":
Listbox_text_Update(listBox1, Convert.ToString(newEventTarget["Caption"])+" 裝置已退出");
break;
}
}
}
public static void Listbox_text_Update(ListBox lbox, string s)
{
if (lbox.InvokeRequired)
{
lbox.BeginInvoke(new MethodInvoker(() => Listbox_text_Update(lbox, s)));
}
else
{
lbox.Items.Add(s);
}
}
複製代碼
歡迎光臨 冰楓論壇 (https://bingfong.com/)
Powered by 冰楓