c# PostMessage not sending and no error

自作多情 提交于 2020-01-15 05:33:07

问题


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.


回答1:


Using Win7 64

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:

[DllImport("User32.Dll", EntryPoint = "PostMessageA", SetLastError = true)]
public static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);

PostMessage(winHandle, (uint)WM_KEYDOWN, (IntPtr)66, IntPtr.Zero);

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.



来源:https://stackoverflow.com/questions/4292613/c-sharp-postmessage-not-sending-and-no-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!