开发者

SendMessage vs. WndProc

开发者 https://www.devze.com 2022-12-25 04:10 出处:网络
I\'m trying to extend TextBox control to add watermarking functionality. The example I\'ve found on CodeProject is using imported Sen开发者_运维百科dMessage function.

I'm trying to extend TextBox control to add watermarking functionality. The example I've found on CodeProject is using imported Sen开发者_运维百科dMessage 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消