窃取键盘输入preventing对焦,能够控制 [英] Preventing Focus-able Controls from stealing Keyboard Input
问题描述
我目前工作的一个简单的游戏,是通过覆盖的OnPaint
方法绘制的表格上。游戏需要键盘输入和进行工作完美,直到我决定以增强图形用户界面,并添加几个按钮的形式。
I'm currently working on a simple game that is drawn on a form by overriding the OnPaint
method. The game requires Keyboard input and was working perfectly until I decided to enhance the GUI and add a few Buttons to the form.
我添加了这些按钮的那一刻,形式停止接受任何键盘输入,无论我如何努力的重点是始终上的按钮。这种行为可以通过放置在窗体上的任何关注,能够控制被复制。 (即文本框)
The moment I added these Buttons, the form stopped receiving any Keyboard input, no matter how hard I tried the focus was always on the buttons. This behavior can be replicated by placing any Focus-able Control on the form. (ie. TextBox)
我不需要使用这些按钮任何Kayboard互动,我希望用户与他们进行互动,只有鼠标。
我尝试以下方法来尝试解决这个问题 - 所有这些工作:
I've tried the following techniques to try and get around this problem - none of these worked:
- 1)正常
的KeyDown
的形式和的KeyUp
事件。 (这是这样 我把按钮之前捕获键盘输入。) - 2)覆盖窗体的
的onkeydown
和的onkeyup
事件。 - 3)重写
ProcessCmdKey
- 作品,但不能区分 的KeyUp和的KeyDown事件之间,所以它是不够的我。
- 1) Normal
KeyDown
andKeyUp
events of the form. (This is the way I was capturing Keyboard input before placing the buttons.) - 2) Overriding the Form's
OnKeyDown
andOnKeyUp
events. - 3) Overriding
ProcessCmdKey
- Works, but cannot differentiate between KeyUp and KeyDown events, so it is inadequate for me.
我也尝试创建一个MessageFilter的应用程序,但我不能强迫它仅捕获,我需要的键盘按键。
I also tried create a MessageFilter for the application, but I couldn't force it to capture only the Keyboard keys that I needed.
我一直在寻找到这几个小时已经并不能找到一个合适的解决方案。 帮助将不胜AP preciated。
I've been looking into this for many hours already and can't find a suitable solution. Help would be greatly appreciated.
推荐答案
下面是一个示例形式的 IMessageFilter
的向上和向下箭头键,希望这有助于:
Here is a sample form with a IMessageFilter
for the up and down arrow keys, hope this helps:
public partial class MainForm : Form
{
private class MessageFilter : IMessageFilter
{
public MainForm Main { get; set; }
public bool PreFilterMessage(ref Message msg)
{
const int WM_KEYDOWN = 0x100;
const int WM_KEYUP = 0x101;
if (msg.Msg == WM_KEYDOWN)
{
var keyData = (Keys)msg.WParam;
if (keyData == Keys.Down || keyData == Keys.Up)
{
return true; // Process keys before return
}
}
else if (msg.Msg == WM_KEYUP)
{
var keyData = (Keys)msg.WParam;
if (keyData == Keys.Down || keyData == Keys.Up)
{
return true; // Process keys before return
}
}
return false;
}
}
public MainForm()
{
this.InitializeComponent();
Application.AddMessageFilter(new MessageFilter { Main = this });
}
}
有关可能的Windows消息的列表查询:
For a list of possible Windows messages check:
这篇关于窃取键盘输入preventing对焦,能够控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!