繁体   English   中英

C#中的闪存驱动器检测器

[英]Flash drive detector in c#

我在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);

这将返回当前可访问的可移动设备。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM