从 user32.dll EnumDisplayDevices 取回坏字符串

我正在尝试从 user32 获取我的监视器的名称。到目前为止,我所得到的都是汉字。我不确定为什么,任何帮助将不胜感激。


    public static SafeNativeMethods.DISPLAY_DEVICE GetDevices()

    {

        SafeNativeMethods.DISPLAY_DEVICE d = new SafeNativeMethods.DISPLAY_DEVICE();

        d.Initialize();

        if (SafeNativeMethods.EnumDisplayDevices(null, 1, ref d, 0))

            return d;

        else

            throw new InvalidOperationException(GetLastError());

    }


public static class SafeNativeMethods

{

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]

    public struct DISPLAY_DEVICE

    {

        [MarshalAs(UnmanagedType.U4)]

        public int cb;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]

        public string DeviceName;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]

        public string DeviceString;

        [MarshalAs(UnmanagedType.U4)]

        public int StateFlags;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]

        public string DeviceID;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]

        public string DeviceKey;

        public void Initialize()

        {

            this.DeviceName = new string(new char[32]);

            this.DeviceString = new string(new char[128]);

            this.DeviceID = new string(new char[128]);

            this.DeviceKey = new string(new char[128]);

            this.cb = (ushort)Marshal.SizeOf(this);

        }

    }




        [DllImport("User32.dll", SetLastError = true, BestFitMapping = false, ThrowOnUnmappableChar = true)]

        public static extern Boolean EnumDisplayDevices(

            [param: MarshalAs(UnmanagedType.LPTStr)]

            String lpDevice,

            [param: MarshalAs(UnmanagedType.U4)]

            Int32 iDevNum,

            [In, Out]

            ref DISPLAY_DEVICE lpDisplayDevice,

            [param: MarshalAs(UnmanagedType.U4)]

            Int32 iHaveNoIdea

        );

}

此代码返回设备名称屜尮䥄偓䅌㉙任何人都可以解释为什么以及如何从中获取正常名称吗?


烙印99
浏览 101回答 1
1回答

LEATH

“中文字符”通常意味着您试图将 ASCII 字符串解释为 Unicode (UTF-16)。尝试在您的声明中添加一个CharSet属性。EnumDisplayDevices
打开App,查看更多内容
随时随地看视频慕课网APP