如果您正在等待设备状态的变化,例如 CD 插入/移除,则收听WM_DEVICECHANGE
消息将是更好的方法。
WM_DEVICECHANGE
当新设备或媒体(如 CD 或 DVD)添加并可用时,以及现有设备或媒体被移除时,Windows 会向所有顶级窗口发送一组默认消息...阅读更多
尝试使用以下帮助程序类来监听媒体插入/删除:
驾驶助手
public static class DriveHelper
{
const int WM_DEVICECHANGE = 0x0219;
const int DBT_DEVICEARRIVAL = 0x8000;
const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
const int DBT_DEVTYP_VOLUME = 0x00000002;
const ushort DBTF_MEDIA = 0x0001;
[StructLayout(LayoutKind.Sequential)]
struct DEV_BROADCAST_VOLUME
{
public uint dbch_Size;
public uint dbch_Devicetype;
public uint dbch_Reserved;
public uint dbch_Unitmask;
public ushort dbch_Flags;
}
public class StateChangedEventArgs : EventArgs
{
public StateChangedEventArgs(string drive, bool ready)
{
Drive = drive;
Ready = ready;
}
public string Drive { get; private set; }
public bool Ready { get; private set; }
}
public static void QueryDeviceChange(Message m, Action<StateChangedEventArgs> action)
{
if (action == null || m.Msg != WM_DEVICECHANGE) return;
var devType = Marshal.ReadInt32(m.LParam, 4);
if (devType != DBT_DEVTYP_VOLUME) return;
var lpdbv = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
if (lpdbv.dbch_Flags != DBTF_MEDIA) return;
var eventCode = m.WParam.ToInt32();
var drive = GetFirstDriveFromMask(lpdbv.dbch_Unitmask);
switch (eventCode)
{
case DBT_DEVICEARRIVAL:
action(new StateChangedEventArgs(drive, true));
break;
case DBT_DEVICEREMOVECOMPLETE:
action(new StateChangedEventArgs(drive, false));
break;
}
}
static string GetFirstDriveFromMask(uint mask)
{
int i;
for (i = 0; i < 26; ++i)
{
if ((mask & 0x1) == 0x1)
break;
mask = mask >> 1;
}
return string.Concat((char)(i + 65), @":\");
}
}
使用示例 (适用于Windows Forms
应用程序)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void OnStateChanged(DriveHelper.StateChangedEventArgs e)
{
// do your work here
MessageBox.Show(string.Format("Drive: {0} => e.Ready: {1}, DriveInfo.IsReady: {2}", e.Drive, e.Ready, new DriveInfo(e.Drive).IsReady));
}
protected override void WndProc(ref Message m)
{
DriveHelper.QueryDeviceChange(m, OnStateChanged);
base.WndProc(ref m);
}
}