【发布时间】:2017-10-16 17:25:03
【问题描述】:
所以在我的程序中,我希望一个对象根据按下的箭头键向左或向右移动。我移动了它们底部的图片框,所以当按下两个箭头键中的任何一个时,它们会沿着底部移动。但是发生的情况是,当我按下任一键时,图片框都会移到顶部并在此处左右移动。我不知道这是为什么。
这是Form1的代码,忽略Form2的代码;现在是为了实验目的:
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 Move
{
public partial class Form1 : Form
{
public int lives = 0;
Form2 menu = new Form2();
public Form1()
{
InitializeComponent();
}
private void button1_KeyDown(object sender, KeyEventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
int i;
for (i = 0; i < 500; i++)
{
if (e.KeyCode == Keys.Left)
{
pictureBox1.Location = new Point(pictureBox1.Left - 1);
Application.DoEvents();
System.Threading.Thread.Sleep(10);
}
if (e.KeyCode == Keys.Right)
{
pictureBox1.Location = new Point(pictureBox1.Left + 1);
Application.DoEvents();
System.Threading.Thread.Sleep(10);
}
var rect1 = new System.Drawing.Rectangle(pictureBox1.Location, pictureBox1.Size);
var rect2 = new System.Drawing.Rectangle(pictureBox2.Location, pictureBox2.Size);
if (rect1.IntersectsWith(rect2))
{
MessageBox.Show("Game Over!");
System.Threading.Thread.Sleep(1000);
Application.Exit();
}
if (e.KeyCode == Keys.Down)
{
this.Hide();
menu.Show();
}
}
}
}
}
【问题讨论】:
-
一个点通常需要 2 个参数。如果你不通过第二个,它显然默认为 0。y = 0 是你的窗口窗体的顶部。将您的新点更改为
new Point(pictureBox1.Left +/- 1, pictureBox1.Top)。
标签: c# winforms picturebox