将密钥发送到非活动窗口?
我想在我的应用程序中发送像“a”这样的键,而不是像 Shift 这样的击键,这类似于屏幕键盘。我使用了这段代码,但它不起作用:
IntPtr p = FindWindow(null, <myWindowTitle>);
ShowWindow(GetWindow(p, 3), 5);
SendKeys.SendWait("a");
但我仍然无法将密钥发送到前一个窗口!
I want to send keys like "a", not keystrokes like Shift in my application, which is something like On-Screen Keyboard. I used this code but it is not working:
IntPtr p = FindWindow(null, <myWindowTitle>);
ShowWindow(GetWindow(p, 3), 5);
SendKeys.SendWait("a");
but still I cannot send keys to the previous window!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您所描述的实际上与屏幕键盘完全不同。它将击键发送到活动窗口。请注意,OSK 永远无法真正接收输入焦点,这完全是设计使然。
SendKeys
仅将输入发送到活动窗口。在 Windows UI 模型中,这是唯一可以接收键盘/鼠标输入的窗口。这就是首先区分“活动”/“聚焦”窗口的全部意义。如果不确切知道您想要实现什么目标,就很难针对您的问题提出替代解决方案。一些想法:
没有理由重新实施 OSK;它与所有版本的 Windows 捆绑在一起,因此您只需使用
Process.Start
启动它即可确保一切正常。如果您确实需要自己做这样的事情,请考虑复制其设计并防止您的输入窗口获得焦点。这将强制接收键盘事件的窗口保持焦点并允许其接收该输入。
或者,您可以调用
SetForegroundWindow 函数
来激活接收键盘输入的窗口,但我不推荐这样做。
What you describe is actually nothing like the On-Screen Keyboard. It sends the keystrokes to the active window. Note that the OSK can never actually receive the input focus, and that's entirely by design.
SendKeys
only sends input to the active window. In the Windows UI model, that's the only window that can receive keyboard/mouse input. That's the whole point of having the 'active'/'focused' window distinction in the first place.It's difficult to propose an alternative solution to your problem without knowing precisely what you're trying to accomplish. Some ideas:
There's no reason to re-implement the OSK; it's bundled with all versions of Windows, so you can simply start it with
Process.Start
and be certain that all will work fine.If you do need to do something like this yourself, look into copying its design and preventing your input window from ever receiving the focus. This will force the window that is to receive the keyboard events to maintain the focus and allow it to receive that input.
Alternatively, you could call the
SetForegroundWindow
function to activate the window that is to receive the keyboard input, but I don't recommend this.