SendMessage 在 C# 中不起作用
我正在尝试从我的应用程序在活动窗口上打印字母“a”:
[DllImport("user32.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);
}
但是该字母没有出现在活动窗口中(对于任何应用程序)。有人可以帮助我吗?
I'm trying to print letter "a" on the active window from my application:
[DllImport("user32.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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
发送 WM_KEYDOWN 和 WM_KEYUP 不起作用,特别是对于字符键。应用程序的消息泵调用 TranslateMessage,后者为这些键生成 WM_CHAR。应用程序通常会查找 WM_CHAR 来查找字符输入。
注入输入的正确方法是使用 SendInput 函数。
这是我通过谷歌搜索找到的 SendInput 包装器。
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.
您必须使用 PostMessage,而不是 SendMessage。你的 pinvoke 声明也是错误的,返回值和最后 2 个参数是 IntPtr,而不是 int。
最终的缺点是您无法控制修饰键 Ctrl、Shift 和 Alt 的状态。这使得此操作随机失败,具体取决于用户是否按下了这些键之一。 SendInput 是必需的,迫使您现在也使用 SetForegroundWindow() 获得正确的焦点。在 Winforms 应用程序中使用 SendKeys。
要注入键入键,您可以使用 SendMessage() 发送 WM_CHAR。
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.