用键盘移动图片框

时间:2016-06-10 23:52:06

标签: c# picturebox

我对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 个答案:

答案 0 :(得分:1)

您的代码有两个问题:

  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坐标。

  3. 所有在一起:

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

答案 1 :(得分:0)

您需要将表单的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);
        }
    }
}
相关问题