使用箭头键移动PictureBox-处理PictureBox中的键盘事件 [英] Move PictureBox using Arrow Keys - Handle keyboard events in PictureBox
问题描述
我有一个PictureBox
,使用下面的代码移动对象.我需要在表单中添加一些按钮,但是,当我启动程序时,箭头键会在按钮中导航,而不是在输入按键中导航.我已经尝试了很多
Form.Load()
上的PictureBox.Focus()
和PictureBox.Select()
之类的方法,并在此处上完全禁用此答案上的箭头键导航,但是对象将不再移动.
I have a PictureBox
where I use the code below to move my object. I need to add a few buttons in the form, however when I start the program the arrow keys navigate through the buttons instead of my input keypresses. I've tried many
ways like PictureBox.Focus()
and PictureBox.Select()
on Form.Load()
, and disabling the arrow key navigation completely on this answer here, but my object will not move anymore.
private void UpdateScreen(object sender, EventArgs e) {
if (Input.KeyPressed(Keys.Right) && Settings.direction != Direction.Left) {
Settings.direction = Direction.Right;
}
else if (Input.KeyPressed(Keys.Left) && Settings.direction != Direction.Right) {
Settings.direction = Direction.Left;
}
else if (Input.KeyPressed(Keys.Up) && Settings.direction != Direction.Down) {
Settings.direction = Direction.Up;
}
else if (Input.KeyPressed(Keys.Down) && Settings.direction != Direction.Up) {
Settings.direction = Direction.Down;
}
}
如何仅禁用所有按钮的箭头键导航,而又不影响UpdateScreen()
中的代码?
How do I just disable the arrow key navigation for all my buttons without affecting my code in UpdateScreen()
?
推荐答案
PictureBox
控件不是Selectable
,因此无法处理键盘事件.要解决此问题,您首先应该使控件变为可选:
PictureBox
control is not Selectable
and therefore it can not handle Keyboard events. To solve the problem, you should first make the control selectable:
using System;
using System.Windows.Forms;
class SelectablePictureBox : PictureBox
{
public SelectablePictureBox()
{
SetStyle(ControlStyles.Selectable, true);
SetStyle(ControlStyles.UserMouse, true);
TabStop = true;
}
protected override void OnEnter(EventArgs e)
{
base.OnEnter(e);
this.Invalidate();
}
protected override void OnLeave(EventArgs e)
{
base.OnLeave(e);
this.Invalidate();
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
if (this.Focused)
ControlPaint.DrawFocusRectangle(pe.Graphics, ClientRectangle);
}
}
然后您可以处理它的PreviewKeyDown
事件:
Then you can handle PreviewKeyDown
event of it:
private void selectablePictureBox1_PreviewKeyDown(object sender,
PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
e.IsInputKey = true;
myPictureBox1.Left -= 10;
}
else if (e.KeyCode == Keys.Right)
{
e.IsInputKey = true;
myPictureBox1.Left += 10;
}
}
这篇关于使用箭头键移动PictureBox-处理PictureBox中的键盘事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!