c#中的闪存驱动器检测器
本文关键字:驱动器 检测器 闪存 | 更新日期: 2023-09-27 18:17:20
我在c#中寻找一个闪存驱动器检测器,我看到了很多例子,但没有一个是简单的或有注释。我试过使用这个代码:
protected override void WndProc(ref Message m)
{
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) )
{
MessageBox.Show(DriveMaskToLetter(vol.dbcv_unitmask).ToString());
}
if ((m.WParam.ToInt32() == DBT_DEVICEREMOVALCOMPLETE) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
{
MessageBox.Show("usb out");
}
}
base.WndProc(ref m);
}
[StructLayout(LayoutKind.Sequential)] //Same layout in mem
public struct DEV_BROADCAST_VOLUME
{
public int dbcv_size;
public int dbcv_devicetype;
public int dbcv_reserved;
public int dbcv_unitmask;
}
private static char DriveMaskToLetter(int mask)
{
char letter;
string drives = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //1 = A, 2 = B, 3 = C
int cnt = 0;
int pom = mask / 2;
while (pom != 0) // while there is any bit set in the mask shift it right
{
pom = pom / 2;
cnt++;
}
if (cnt < drives.Length)
letter = drives[cnt];
else
letter = '?';
return letter;
}
如果有人能帮忙的话,我将非常感激。
var drives = DriveInfo.GetDrives().Where(x=> x.IsReady && x.DriveType == DriveType.Removable);
返回当前可访问的可移动设备。