Search code examples
c#stringinteropmarshallingintptr

IntPtr To String conversion in Windows messages


I'm getting in trouble by hooking window messages. I need to detect window text (caption) changes, so I intercept the WM_SETTEXT message for the interesting windows (I do so because at window creation the window caption is not specified).

Reading the documentation of the WM_SETTEXT documentation, the lParam parameter specify a pointer to the string representing the window text.

The message is forwarded to a .NET application using SendMessage. What I do in the .NET application is:

private static bool ProcessMessage(ref Message msg) {
    ...
    string s = Marshal.PtrToStringAuto(msg.LParam) *
}

where ProcessMessage is the routine handling messages of the .NET form.

What I always get is an empty string, which is not the expected result. I tried other Marshal.PtrToString* methods, but no one has worked.

What am I doing wrong in the conversion of a IntPtr to String?

(*)Note that I cannot debug this code, since it would block the entire system, since all windows messages are intercepted.


Solution

  • LParam is a string pointer, and your code is correct, assuming that it is executed in the same process where WM_SETTEXT message was sent. In another process, this pointer is invalid, and result of using this pointer is undefined.