[英]Getting back bad strings from 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
);
}
此代碼返回設備名稱屜尮䥄偓䅌㉙
任何人都可以解釋為什么以及如何從中獲取正常名稱?
“中文字符” 通常表示您嘗試將ASCII字符串解釋為Unicode (UTF-16)。
嘗試將CharSet
屬性添加到EnumDisplayDevices
聲明中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.