用键盘移动图片框

Move picturebox with keyboard

我是 c# 的新手,我想在按下 WASD 键时让图片框移动,但图片框拒绝移动。图片框未停靠、锁定或锚定。这是我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Imagebox_test1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            int x = pictureBox1.Location.X;
            int y = pictureBox1.Location.Y;

            if (e.KeyCode == Keys.D) x += 1;
            else if (e.KeyCode == Keys.A) x -= 1;
            else if (e.KeyCode == Keys.W) x -= 1;
            else if (e.KeyCode == Keys.S) x += 1;

            pictureBox1.Location = new Point(x, y);
        }
    }
}

我不知道发生了什么!感谢您的帮助!

您的代码有 2 个问题:

  1. 将表单的 KeyPreview 属性 设置为 true 否则 PictureBox 将获得 KeyDown 事件。这阻止了 Form1_KeyDown 被调用。
  2. 这个代码块有一个微妙的错误:

    if (e.KeyCode == Keys.D) x += 1;
    else if (e.KeyCode == Keys.A) x -= 1;
    else if (e.KeyCode == Keys.W) x -= 1;
    else if (e.KeyCode == Keys.S) x += 1;
    

    如果你仔细观察,你只是在修改 x 坐标。

总计:

public Form1()
{
    InitializeComponent();

    // Set these 2 properties in the designer, not here.
    this.KeyPreview = true;
    this.KeyDown += Form1_KeyDown;
}

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    int x = pictureBox1.Location.X;
    int y = pictureBox1.Location.Y;

    if (e.KeyCode == Keys.D) x += 1;
    else if (e.KeyCode == Keys.A) x -= 1;
    else if (e.KeyCode == Keys.W) y -= 1;
    else if (e.KeyCode == Keys.S) y += 1;

    pictureBox1.Location = new Point(x, y);
}

您需要将表单的 KyePreview 属性 设置为 true,否则表单将不会接受该按键按下事件。 其次你只是改变 x 值而不是 y 值。 完整的代码为

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Imagebox_test1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
KeyPreview = true; 
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            int x = pictureBox1.Location.X;
            int y = pictureBox1.Location.Y;

            if (e.KeyCode == Keys.D) x += 1;
            else if (e.KeyCode == Keys.A) x -= 1;
            else if (e.KeyCode == Keys.W) y -= 1;
            else if (e.KeyCode == Keys.S) y += 1;

            pictureBox1.Location = new Point(x, y);
        }
    }
}