控制移动图片框
本文关键字:移动 控制 | 更新日期: 2023-09-27 17:56:32
所以,我有点卡在我的移动图片盒上;在我的表格 2 加载图片框的那一刻,图片框开始移动,这正是我想要的,然而它不在我的控制范围内,这就是我试图做的,但我失败了......我想要的只是由按键控制的运动画面盒的方向......谢谢。
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 Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
timer1.Start();
}
private void Form2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Right)
{
pictureBox1.Location = new Point(pictureBox1.Location.X + 5, pictureBox1.Location.Y);
}
if (e.KeyCode == Keys.Up)
{
pictureBox1.Location = new Point(pictureBox1.Location.X, pictureBox1.Location.Y - 5);
}
if (e.KeyCode == Keys.Left)
{
pictureBox1.Location = new Point(pictureBox1.Location.X - 5, pictureBox1.Location.Y);
}
if (e.KeyCode == Keys.Down)
{
pictureBox1.Location = new Point(pictureBox1.Location.X, pictureBox1.Location.Y + 5);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
pictureBox1.Location = new Point(pictureBox1.Location.X + 25, pictureBox1.Location.Y);
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
}
}
你需要一个变量来指示盒子的移动方向:
private enum Direction { None, Left, Right, Up, Down };
private Direction currentDir = Direction.None;
计时器的 Tick 事件需要检查此变量,以了解将框移动到哪个方向:
private void timer1_Tick(object sender, EventArgs e) {
int vel = 5;
switch (currentDir) {
case Direction.Left: pictureBox1.Left -= Math.Min(vel, pictureBox1.Left); break;
case Direction.Right: pictureBox1.Left += Math.Min(vel, this.ClientSize.Width - pictureBox1.Right); break;
case Direction.Up: pictureBox1.Top -= Math.Min(vel, pictureBox1.Top); break;
case Direction.Down: pictureBox1.Top += Math.Min(vel, this.ClientSize.Height - pictureBox1.Bottom); break;
}
}
KeyDown 事件处理程序应仅设置变量:
private void Form1_KeyDown(object sender, KeyEventArgs e) {
switch (e.KeyData) {
case Keys.Left: currentDir = Direction.Left; break;
case Keys.Right: currentDir = Direction.Right; break;
case Keys.Up: currentDir = Direction.Up; break;
case Keys.Down: currentDir = Direction.Down; break;
}
}
您还需要 KeyUp 事件,它应该再次停止移动框:
private void Form1_KeyUp(object sender, KeyEventArgs e) {
switch (e.KeyData) {
case Keys.Left: if (currentDir == Direction.Left) currentDir = Direction.None; break;
case Keys.Right: if (currentDir == Direction.Right) currentDir = Direction.None; break;
case Keys.Up: if (currentDir == Direction.Up) currentDir = Direction.None; break;
case Keys.Down: if (currentDir == Direction.Down) currentDir = Direction.None; break;
}
}
计时器事件在 UI 线程上引发,因此按键事件的选取速度不够快。
在后台线程上运行计时器,它应该可以工作。请记住,计时器将进行跨线程调用,因此您需要使用 Control.InvokeRequired