Reputation: 1346
I am trying to get the names of my monitors from user32. With what I have so far all I get returned is in Chinese characters. I'm not sure why, any help would be appreciated.
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
);
}
This code returns a device name of 屜尮䥄偓䅌㉙
could anyone please explain why and how to get the normal name from this?
Upvotes: 1
Views: 255
Reputation: 101626
"Chinese characters" usually means you tried to interpret a ASCII string as Unicode (UTF-16).
Try adding a CharSet
property to your EnumDisplayDevices
declaration.
Upvotes: 3