Windows 消息中的 IntPtr 到 String 转换
我因挂钩窗口消息而遇到麻烦。我需要检测窗口文本(标题)更改,因此我拦截感兴趣窗口的 WM_SETTEXT 消息(我这样做是因为在创建窗口时未指定窗口标题)。
阅读 WM_SETTEXT 文档的文档, lParam 参数指定指向表示窗口文本的字符串的指针。
使用 SendMessage 将消息转发到 .NET 应用程序。我在 .NET 应用程序中所做的是:
private static bool ProcessMessage(ref Message msg) {
...
string s = Marshal.PtrToStringAuto(msg.LParam) *
}
其中 ProcessMessage 是处理 .NET 表单消息的例程。
我总是得到一个空字符串,这不是预期的结果。我尝试了其他 Marshal.PtrToString* 方法,但没有人工作。
在将 IntPtr 转换为 String 时我做错了什么?
(*)请注意,我无法调试此代码,因为它会阻止整个系统,因为所有 Windows 消息都被拦截。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
LParam 是一个字符串指针,并且您的代码是正确的,假设它是在发送 WM_SETTEXT 消息的同一进程中执行的。在另一个进程中,该指针无效,并且使用该指针的结果是未定义的。
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.
它可能是一个指向字符指针的指针。
因此,读取 IntPtr,读取 IntPtr 中的值(也是 IntPtr),然后像您一样使用它。
也许有效,也许无效:p
It is probably a pointer to a pointer of chars.
So read the IntPtr, the read the value in IntPtr which is also IntPtr, then use that as you did.
Maybe it works, maybe it doesn't :p