DBT_DEVICEARRIVAL获取guid C#

时间:2015-12-05 18:06:36

标签: c# winapi

我有这个C#代码:

private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
        const int WM_DEVICECHANGE = 0x0219;
        const int DBT_DEVICEARRIVAL = 0x8000;

        if(msg == WM_DEVICECHANGE)
        {
            if(wParam.ToInt32() == DBT_DEVICEARRIVAL)
            {
                // get GUID of inserted device
            }
        }

        return IntPtr.Zero;
}

并在线评论为" //获取插入设备的GUID"我需要获取当前设备GUID。我该怎么办?

1 个答案:

答案 0 :(得分:0)

可能这不是一个更好的解决方案,但我确实喜欢这个

if (wParam.ToInt32() == DBT_DEVICEARRIVAL)
{
    DEV_BROADCAST_HDR pHdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(lParam, typeof(DEV_BROADCAST_HDR));
    if (pHdr.dbch_DeviceType == 2)
    {
        DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(lParam, typeof(DEV_BROADCAST_VOLUME));
        char letter = UnitName(vol.dbcv_unitmask);
        // here we get drive mount point from bitmask
        string name = DriveLetter(letter);
        int bufferCapacity = 256;
        StringBuilder res = new StringBuilder(bufferCapacity);
        // using drive mount point we can get structure that describes this drive
        GetVolumeNameForVolumeMountPoint(name,res,(uint) bufferCapacity);
        Guid g = Guid.Parse(res.ToString().Substring(11,36));
        Reducer.RememberCurrentDrive(g,letter);
    }
}

这就是我所需要的一切。谢谢你的帮助。