c# PostMessage 未发送且没有错误
首先, 我正在尝试将键盘输入发送到后台应用程序(没有焦点或者甚至可能对用户不可见的窗口)。
我已经验证 winHandle 和常量是正确的。 问题是后台应用程序似乎没有收到消息,除非, 我在 PostMessage() 行上设置一个断点,并在到达那里时按 F10(跳过)或 F5(继续), 然后击键就神奇地被发送了。
什么给? 相关代码:
[DllImport("User32.Dll", EntryPoint = "PostMessageA", SetLastError = true)]
public static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);
PostMessage(winHandle, (uint)WM_KEYDOWN, 66, 0);
使用Win7 64和MS Visual studio 2008 pro,控制台应用程序。如果有帮助的话,上面的代码位于线程上。
First off,
I'm trying to send keyboard input to a background application(A window that does'nt have focus or might not even appear visible to the user).
I've verified that the winHandle and constants are correct.
Problem is the background application doesn't seem to get the message, UNLESS,
I set a breakpoint on the PostMessage() line, and press F10(step over) or F5(Continue) when it gets there,
then the keystroke magically gets sent.
What gives?
Relevant code:
[DllImport("User32.Dll", EntryPoint = "PostMessageA", SetLastError = true)]
public static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);
PostMessage(winHandle, (uint)WM_KEYDOWN, 66, 0);
Using Win7 64 and MS Visual studio 2008 pro, Console application. And the above code is on a Thread if that helps.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这有点相关,声明是错误的。在32位模式下可以工作,但在64位模式下就很麻烦。最后两个参数是指针,而不是整数。 8 个字节,而不是 4 个字节。 修复:
但是,这可能并不能真正解决您的问题。在 x64 模式下,非实例方法的前 4 个参数在寄存器中传递,而不是在堆栈中传递。碰巧这个方法有 4 个参数,您不会收到 PInvokeStackImbalance MDA 警告。而且 64 位寄存器值的高 32 位通常会意外为零,因此 P/Invoke 编组器生成 32 位还是 64 位参数值并不重要。
请注意,这种方法在实践中相当麻烦。您无法控制目标进程中键盘的状态。您正在发送 B 的击键。这可能会变成 B、b、Alt+B 或 Ctrl+B,具体取决于修饰键的状态。只有SendInput()可以可靠地工作。好吧,短距离窗口焦点问题。
That's somewhat relevant, the declaration is wrong. Works in 32-bit mode, but troublesome in 64-bit mode. The last two arguments are pointers, not ints. 8 bytes, not 4. Fix:
However, this may not actually solve your problem. In x64 mode, the first 4 arguments of a non-instance method are passed in registers, not the stack. It just so happens that this method has 4 arguments, you won't get the PInvokeStackImbalance MDA warning. And the upper 32-bits of the 64-bit register values are often zero by accident so it doesn't matter whether the P/Invoke marshaller generates a 32-bit or a 64-bit argument value.
Beware that this approach is quite troublesome in practice. You cannot control the state of the keyboard in the target process. You are sending the keystroke for B. That may turn into B, b, Alt+B or Ctrl+B, depending on the state of the modifier keys. Only SendInput() can work reliably. Well, short from the window focus problem.