[英]How to detect a USB HDD programatically using c#
嗨,我必須開發一個使用C#檢測USB HDD的應用程序。 可能嗎?。 我有一個用於檢測USB Mass Storage設備的代碼。 我添加了對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;
}
}
}
}
我為USB Pen驅動器開發了一個應用程序,下面是我的聲明:
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
{
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.