在 C# 中使窗体不可聚焦
我想编写一个虚拟键盘,例如触摸屏电脑的 Windows 屏幕键盘。 但我的虚拟键盘从正在使用的应用程序中窃取焦点时遇到问题。即使用户单击当前应用程序,Windows 屏幕键盘也会将焦点保留在当前应用程序上。有没有办法在 C# 中对 Windows 窗体执行相同的操作?
我现在唯一能做的就是将键盘事件发送到特定的应用程序,例如以下代码中的记事本。如果我可以使窗体不可聚焦,我可以使用 GetForegroundWindow 获取当前聚焦的窗口。
[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName,string lpWindowName);
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
private void button1_Click(object sender, EventArgs e)
{
IntPtr calculatorHandle = FindWindow("notepad", null);
SetForegroundWindow(calculatorHandle);
SendKeys.SendWait("111");
}
有办法做到这一点吗?有什么更好的方法让表单将键盘事件发送到正在使用的应用程序的建议吗?
谢谢!!
I'm wanting to write a virtual keyboard, like windows onscreen keyboard for touchscreen pcs.
But I'm having problem with my virtual keyboard stealing the focus from the application being used. The windows onscreen keyboard mantains the focus on the current application even when the user clicks on it. Is there a way to do the same with windows forms in C#?
The only thing I can do for now is to send a keyboard event to an especific application, like notepad in the following code. If I could make the form not focusable, I could get the current focused window with GetForegroundWindow.
[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName,string lpWindowName);
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
private void button1_Click(object sender, EventArgs e)
{
IntPtr calculatorHandle = FindWindow("notepad", null);
SetForegroundWindow(calculatorHandle);
SendKeys.SendWait("111");
}
Is there a way this can be done? Any suggestions of a better way to have the form sending keyboard events to the application being used?
Thanks!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解决了!
我已经尝试了 gehho 的解决方案,但我还需要重写
CreateParams
方法:Its solved!
I've tried the solution from gehho, but I also needed to override the
CreateParams
method:我宁愿尝试阻止您的窗口接收焦点/被激活,而不是在单击您的窗口后尝试重置活动窗口。
请查看本文。最后,作者简要解释了如何做到这一点:
此外,在这篇文章中,他提供了一个代码示例对于 Windows 窗体:
Instead of trying to reset the active window after your one has been clicked, I would rather try to prevent your window from receiving focus/being activated.
Have a look at this article. At the end, the author briefly explains how this can be done:
Furthermore, in this article he provides a code example for Windows Forms: