问题描述
我目前正在开发一个有面板的winform。我需要能够使用面板上的向上,向下,向左和向右箭头,并发现某些事情。
I am currently working on winform that has a panel on it. I need to be able to use the up, down, left and right arrows on the panel and get something to happen.
我尝试使用这一行代码添加事件:
I tried adding the event with this line of code:
(MainPanel as Control).KeyDown +=
new KeyEventHandler(panelKeyPressEventHandler);
使用此KeyDown代码:
With this KeyDown code:
public void panelKeyPressEventHandler(object sender, System.Windows.Forms.KeyEventArgs e)
{
MessageBox.Show("Here I am!");
switch (e.KeyCode)
{
case Keys.L:
{
break;
}
case Keys.R:
{
break;
}
case Keys.Up:
{
break;
}
case Keys.Down:
{
break;
}
case Keys.Right:
{
break;
}
case Keys.Left:
{
break;
}
}
}
,即使我保证在面板上设置焦点,我无法让它进入这个KeyDown事件功能的任何东西。 (我可以整天打键,没有任何反应。
Thus far, even when I guarantee focus is set on the panel, I am unable to get it to enter this KeyDown event function for anything. :( I can hit keys all day long and nothing happens.
有没有人有任何建议,最好的方法来处理上,下,左,右箭头被按下一个面板有焦点?
Does anyone have any suggestion on the best way to handle up,down,left and right arrows being pressed when a panel has focus?
谢谢!
推荐答案
面板控件您可能需要覆盖您的表单中的 ProcessCmdKey
或 UserControl
。
Panel control cannot get focus and not selectable also. Focused controls can only get "key events". You likely need to override ProcessCmdKey
in your form or UserControl
.
您需要设置 KeyPreview = true
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
switch(keydata)
{
case Keys.Up:
break;
...
}
return base.ProcessCmdKey(ref msg, keyData);
}
这篇关于在Panel中创建KeyDown事件的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!