使用箭头键移动 PictureBox - 处理 PictureBox 中的键盘事件

2023-11-29

我有一个PictureBox我使用下面的代码来移动我的对象。我需要在表单中添加一些按钮,但是当我启动程序时,箭头键在按钮中导航,而不是我的输入按键。我尝试过很多 像这样的方式PictureBox.Focus() and PictureBox.Select() on Form.Load(),并在此答案上完全禁用箭头键导航here,但我的物体将不再移动。

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()?


PictureBox控制不是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它的事件:

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;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用箭头键移动 PictureBox - 处理 PictureBox 中的键盘事件 的相关文章