开发者

SendMessage doesn't work from C#

I'm trying to print letter "a" on the active window from my application:

[DllImport("us开发者_开发技巧er32.dll")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

...

// global hotkey handler
void hook_KeyPressed(object sender, KeyPressedEventArgs e)
{
    var hWnd = GetForegroundWindow();

    SendMessage(hWnd, (uint)WM.KEYDOWN, (int)VK.KEY_A, 0);
    SendMessage(hWnd, (uint)WM.KEYUP, (int)VK.KEY_A, 0);
 }

But letter doesn't appear in active window (for any application). Can anybody help me?


Sending WM_KEYDOWN and WM_KEYUP doesn't work, especially for character keys. An application's message pump calls TranslateMessage which generates WM_CHAR for those keys. It is usually WM_CHAR that the application looks at for character input.

The correct way to inject input is to use the SendInput function.

Here's a SendInput wrapper I found by googling.


You have to use PostMessage, not SendMessage. Your pinvoke declaration is wrong too, the return value and the last 2 arguments are IntPtr, not int.

The ultimate downfall is that you cannot control the state of the modifier keys, Ctrl, Shift and Alt. Which makes this randomly fail, depending on whether or not the user has one of those keys pressed. SendInput is required, forcing you now to also get the focus correct with SetForegroundWindow(). Use SendKeys in a Winforms app.

To inject typing keys you can use SendMessage() to send WM_CHAR.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜