您好我必须开发一个使用C#检测USB HDD的应用程序。可能吗?。我有一个用于检测USB大容量存储设备的代码。 我添加了对System.Runtime.InteropServices的引用 我试图覆盖WndProc()方法。我将包含代码段
protected override void WndProc(ref Message message)
{
base.WndProc(ref message);
if ((message.Msg != WM_DEVICECHANGE) || (message.LParam == IntPtr.Zero))
return;
DEV_BROADCAST_VOLUME volume = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(message.LParam, typeof(DEV_BROADCAST_VOLUME));
if (volume.dbcv_devicetype == DBT_DEVTYP_VOLUME)
{
switch (message.WParam.ToInt32())
{
// New device inserted...
case DBT_DEVICEARRIVAL:
MessageBox.Show(
string.Format("A storage device has been inserted; Drive :{0}", ToDriveName(volume.dbcv_unitmask)), "Detect USB");
break;
// Device Removed.
case DBT_DEVICEREMOVECOMPLETE:
MessageBox.Show("Storage has been removed.", "Detect USB");
break;
}
}
}
}
答案 0 :(得分:1)
我开发了以下USB笔式驱动器的应用程序是我的声明:
const int WM_DEVICECHANGE = 0x0219;
const int DBT_DEVICEARRIVAL = 0x8000;
const int DBT_DEVICEREMOVALCOMPLETE = 0x8004;
const int DBT_DEVTYPVOLUME = 0x00000002;
以下是我对WinProc
:
protected override void WndProc(ref Message m)
{
try
{
if (m.Msg == WM_DEVICECHANGE)
{
DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
if ((m.WParam.ToInt32() == DBT_DEVICEARRIVAL) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
{
usb_drive = DriveMaskToLetter(vol.dbcv_unitmask).ToString();
if (usb_drive.Replace(" ", "").Length > 0)
{
// USB Inserted
}
}
if ((m.WParam.ToInt32() == DBT_DEVICEREMOVALCOMPLETE) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
{
//USB Removed
}
}
base.WndProc(ref m);
}
catch
{
}
}