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

时间:2018-01-21 13:05:10

标签: c# .net winforms picturebox keypress

我有PictureBox我使用下面的代码来移动我的对象。我需要在表单中添加几个按钮,但是当我启动程序时,箭头键会导航按钮而不是我的输入按键。我试过很多次 PictureBox.Focus()上的PictureBox.Select()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()中的代码?

1 个答案:

答案 0 :(得分:3)

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;
    }
}