SendMessage 与 WndProc
我正在尝试扩展 TextBox
控件以添加水印功能。我在 CodeProject 上找到的示例使用导入的 SendMessage 函数。
[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");
}
我想知道为什么不使用 protected WndProc 来代替
void SetWatermark()
{
var m =new Message() { HWnd = this.Handle, Msg = 0x1501, WParam = (IntPtr)0, LParam = Marshal.StringToHGlobalUni("Sample") };
WndProc(ref m);
}
两者似乎都工作正常。我在互联网上看到的几乎所有示例都使用 SendMessage
函数。这是为什么? WndProc
函数不是为了取代 SendMessage
而设计的吗?
PS 我不知道将 string
转换为 IntPtr
的正确方法,并发现 Marshal.StringToHGlobalUni
工作正常。这样做是正确的功能吗?
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 SendMessage
function. 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
WndProc
不会取代SendMessage
,它是WindowProc
。WndProc
由应用程序的消息泵(接收由SendMessage
或PostMessage
发送或发布的消息)调用来处理它们。通过直接调用WndProc
,您可以绕过 Windows 执行的特殊消息处理,例如捆绑WM_PAINT
消息,并且可能会导致一些令人讨厌的问题,即消息出现在命令您的应用程序中的窗口需要它们。正如 MSDN 中所述,
通过直接调用它,您将剥夺系统对该消息执行预处理或任何其他处理的机会。 .NET 框架在 Windows 之上运行,如果不发送或发布消息,底层系统就无法对该消息执行任何操作,因此您会失去底层系统可能为您执行的任何操作。
WndProc
does not replaceSendMessage
, it is the .NET equivalent ofWindowProc
.WndProc
is called by your application's message pump (which receives messages that are sent or posted bySendMessage
orPostMessage
) to process them. By callingWndProc
directly, you by-pass the special message handling that Windows performs, such as bundlingWM_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,
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.