WinForms 應用程式可透過覆寫 `WndProc` 攔截 Windows 訊息 `WM_DEVICECHANGE (0x219)`,偵測 USB 裝置插入/移除。本文提供完整可用程式碼,並說明如何取得磁碟機代號、卷標、檔案系統類型。
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public partial class MainForm : Form
{
// Windows 訊息常數
private const int WM_DEVICECHANGE = 0x0219;
private const int DBT_DEVICEARRIVAL = 0x8000; // 裝置插入
private const int DBT_DEVICEREMOVECOMPLETE = 0x8004; // 裝置移除完成
private const int DBT_DEVTYP_VOLUME = 0x00000002; // 邏輯磁碟機
// DEV_BROADCAST_VOLUME 結構 (用於解析 lParam)
[StructLayout(LayoutKind.Sequential)]
private struct DEV_BROADCAST_VOLUME
{
public int dbcv_size;
public int dbcv_devicetype;
public int dbcv_reserved;
public int dbcv_unitmask; // 位元遮罩:bit 0 = A:, bit 1 = B: ...
public short dbcv_flags;
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_DEVICECHANGE)
{
switch ((int)m.WParam)
{
case DBT_DEVICEARRIVAL:
OnDeviceArrival(m.LParam);
break;
case DBT_DEVICEREMOVECOMPLETE:
OnDeviceRemoved(m.LParam);
break;
}
}
}
private void OnDeviceArrival(IntPtr lParam)
{
var vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(lParam, typeof(DEV_BROADCAST_VOLUME));
if (vol.dbcv_devicetype == DBT_DEVTYP_VOLUME)
{
char driveLetter = GetDriveLetterFromMask(vol.dbcv_unitmask);
if (driveLetter != '\0')
{
DriveInfo di = new DriveInfo(driveLetter.ToString());
if (di.IsReady && di.DriveType == DriveType.Removable)
{
string label = di.VolumeLabel;
string fs = di.DriveFormat; // FAT32, NTFS, exFAT
long free = di.AvailableFreeSpace;
long total = di.TotalSize;
// UI 執行緒安全更新
this.BeginInvoke((Action)(() =>
{
lstLog.Items.Insert(0, $"[插入] {driveLetter}:\\ [{label}] {fs} 可用:{free/1024/1024}MB / 總計:{total/1024/1024}MB");
}));
}
}
}
}
private void OnDeviceRemoved(IntPtr lParam)
{
var vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(lParam, typeof(DEV_BROADCAST_VOLUME));
if (vol.dbcv_devicetype == DBT_DEVTYP_VOLUME)
{
char driveLetter = GetDriveLetterFromMask(vol.dbcv_unitmask);
if (driveLetter != '\0')
{
this.BeginInvoke((Action)(() =>
{
lstLog.Items.Insert(0, $"[移除] {driveLetter}:\\");
}));
}
}
}
private char GetDriveLetterFromMask(int unitMask)
{
for (int i = 0; i < 26; i++)
{
if ((unitMask & (1 << i)) != 0)
return (char)('A' + i);
}
return '\0';
}
}
// WPF 需用 HwndSource 添加 Hook
public MainWindow()
{
InitializeComponent();
SourceInitialized += (s, e) =>
{
var hwndSource = PresentationSource.FromVisual(this) as HwndSource;
hwndSource.AddHook(WndProcHook);
};
}
private IntPtr WndProcHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_DEVICECHANGE) { /* 同 WinForms 邏輯 */ }
return IntPtr.Zero;
}
若需偵測**非磁碟機** USB 裝置 (如印表機、HID、序列埠),需呼叫 `RegisterDeviceNotification` 註冊 `DEV_BROADCAST_DEVICEINTERFACE`,並指定 GUID (如 `GUID_DEVINTERFACE_USB_DEVICE`)。此法較複雜,參考 Microsoft 文件「Device Notification」。