在C#编程中用键盘上的方向键来控制一张图片的移动的代码怎么写啊?要简单具体的!!!

2024-12-19 11:14:26
推荐回答(4个)
回答1:

刚做了个简单的:

在Form窗体上添加一个PictureBox1控件

添加Form窗体的KeyDown消息响应函数

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace WindowsFormsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)

        {

            switch (e.KeyCode)

            {

                case Keys.Up:

                    pictureBox1.Top -=5;

                    break;

                case Keys.Down:

                    pictureBox1.Top += 5;

                    break;

                case Keys.Right:

                    pictureBox1.Left += 5;

                    break;

                case Keys.Left:

                    pictureBox1.Left -= 5;

                    break;

                default:

                    break;

            }

        

        }

    }

}

回答2:

使用keyDown事件,
if(e.keycode==keys.Left)
{
//如果按下左键,图片的坐标就左移5个像素
pictureBox.Location=new point (pictureBox.Location.X-5,pictureBox.Location.Y);
}

窗体的坐标原点是在窗体的最左上角,往右X轴加,往下Y轴加

回答3:

首先要实现Form的onKeyDown的事件。
然后在里面这样写:
int dx=10;//以10像素为单位偏移
switch(KeyEvent.KeyCode)
{
case KeyCode.UP:
pictureBox1.Top-=dx;
break;
case KeyCode.Down:
pictureBox1.Top+=dx;
break;
case KeyCode.Left:
pictureBox1.Left-=dx;
break;
case KeyCode.Right:
pictureBox1.Left+=dx;
break;
}
//大致是这个思路。没调试,将就看吧

回答4:

刚做了个简易的,截图发不了,被度娘吞了,有问题可以hi我
在Form窗体上添加一个PictureBox1控件
添加Form窗体的KeyDown消息响应函数
//form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Up:
pictureBox1.Top -=5;
break;
case Keys.Down:
pictureBox1.Top += 5;
break;
case Keys.Right:
pictureBox1.Left += 5;
break;
case Keys.Left:
pictureBox1.Left -= 5;
break;
default:
break;
}

}
}
}