Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SendMessage vs. WndProc

I'm trying to extend TextBox control to add watermarking functionality. The example I've found on CodeProject is using imported SendMessage function.

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);

void SetWatermark()
{
    SendMessage(this.Handle, 0x1501, 0, "Sample");
}

I'm wondering why not use protected WndProc instead

void SetWatermark()
{
    var m =new Message() { HWnd = this.Handle, Msg = 0x1501, WParam = (IntPtr)0, LParam = Marshal.StringToHGlobalUni("Sample") };
    WndProc(ref m);
}

Both seem to work fine. Almost all examples I've seen on internet use SendMessagefunction. Why is that? Isn't WndProc function designed to replace SendMessage?

P.S. I don't know right to convert string to IntPtr and found that Marshal.StringToHGlobalUni works ok. Is it right function to do this?

like image 642
Poma Avatar asked Mar 29 '10 17:03

Poma


1 Answers

WndProc does not replace SendMessage, it is the .NET equivalent of WindowProc. WndProc is called by your application's message pump (which receives messages that are sent or posted by SendMessage or PostMessage) to process them. By calling WndProc directly, you by-pass the special message handling that Windows performs, such as bundling WM_PAINT messages, and can potentially cause some nasty problems where messages appear out of the order that they're expected by windows within your application.

As stated in MSDN,

All messages are sent to the WndProc method after getting filtered through the PreProcessMessage method.

The WndProc method corresponds exactly to the Windows WindowProc function. For more information about processing Windows messages, see the WindowProc function documentation in the MSDN library at http://msdn.microsoft.com/library.

By calling it directly, you deprive the system of a chance to perform preprocessing or any other handling of that message. The .NET framework runs on top of Windows and without sending or posting the message, the underlying system cannot do anything with that message, so you lose out on anything the underlying system might do for you.

like image 68
Jeff Yates Avatar answered Oct 08 '22 17:10

Jeff Yates