将密钥发送到非活动窗口?

发布于 2025-01-04 05:44:02 字数 231 浏览 5 评论 0原文

我想在我的应用程序中发送像“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泪是无色的血 2025-01-11 05:44:02

您所描述的实际上与屏幕键盘完全不同。它将击键发送到活动窗口。请注意,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文