20

I'm new to C# (from a native C++ background) and I'm trying to write a little UI to print windows broadcast messages among other things. I've overridden the default WndProc message loop in my C# program like so:

[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
    protected override void WndProc(ref Message m)
    {
        // Listen for operating system broadcasts.
        switch (m.Msg)
        {
            case WM_SETTINGCHANGE:

                this.richTextLog.Text += "WM_SETTINGCHANGE - lParam=" + m.LParam.ToString() + "\n";

                break;
        }
        base.WndProc(ref m);
    }

What I'd like to know, is how to obtain a string representation of the lParam object which is of type IntPtr. It's essentially a void* in C++ land, can I cast it inside C# somehow? Presumably doing so is inherently unsafe.

Benj
  • 31,668
  • 17
  • 78
  • 127

2 Answers2

31

Marshal.PtrToStringAuto Method (IntPtr)

Allocates a managed String and copies all characters up to the first null character from a string stored in unmanaged memory into it.

GSerg
  • 76,472
  • 17
  • 159
  • 346
8

The above answer was great and it nearly solved the same issue for me but... I got what looks like Chinese characters back from the method (潆湵⁤瑡氠慥瑳漠敮爠灥慥整⁤浩条⁥慮敭›䌢⸢). What I had to do was use the Marshal.PtrToStringAnsi(IntPtr) method as described here: http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.ptrtostringansi.aspx and here: http://answers.unity3d.com/questions/555441/unitys-simplest-plugin-print-does-not-work.html.

Once I made the change, my String was in English once more. Not sure why that was happening, but there ya go!

justian17
  • 575
  • 1
  • 7
  • 17
  • 7
    [From the MSDN](http://msdn.microsoft.com/en-us/library/ewyktcaa.aspx) "*If the current platform is Unicode, each ANSI character is widened to a Unicode character and this method calls PtrToStringUni. Otherwise, this method calls PtrToStringAnsi.*" Your system is a Unicode system but your unmanaged code was returning a Ansi string so the Auto system was choosing the wrong string encoding. – Scott Chamberlain Jan 14 '14 at 15:40
  • @ScottChamberlain, Thanks – AleX_ Sep 29 '16 at 15:37
  • I want to thank Ilia as well, but I cant Tag him for some reason. – AleX_ Sep 29 '16 at 15:39
  • I'm not getting readable chars using PtrToStringAnsi nor PtrToStringAuto :( – Pedro77 Feb 10 '17 at 14:22
  • @Pedro77 Try to call it in the middle of your app (=not as the very first function). Give OGL a second to warm up. Create a viewport first. – Bitterblue Nov 17 '21 at 03:12