我有以下代码。当我点击按钮图片框时,从右到左,从上到下移动。当它移动到面板的末端时,它再次从右到左,从上到下开始。现在的问题是,在第一次完成图片框从右到左计时器速度逐渐增加虽然我把它设置为200也似乎,这行myform.counterTop = myform.counterTop + 5;值5也逐渐增加。在第一轮之后,它增加了一点,在第二轮之后它增加了一点并继续这样。请告诉我为什么会这样。
namespace Spaceship_Invaders
{
public partial class Form1 : Form
{
private int invaderlanded = 0;
private int invaderstopped = 0;
private int counterfortop = -60;
private int counterforleft = 415;
private int counterTop = -60;
private int counterLeft = 415;
private bool pictureboxclicked = false;
private int timerinterval = 200;
System.Windows.Forms.Timer mytimer = new System.Windows.Forms.Timer();
public Form1()
{
InitializeComponent();
Image myImage = Image.FromFile("image/Untitled6.png");
pictureBox1.Image = myImage;
pictureBox1.Top = counterfortop;
pictureBox1.Left = counterforleft;
}
public class Spaceship
{
Form1 myform;
public Spaceship(Form1 form)
{
myform = form;
}
public void mspaceship()
{
myform.mytimer.Tick += new EventHandler(TimerEventProcessor);
myform.mytimer.Interval = myform.timerinterval;
myform.mytimer.Enabled = true;
myform.mytimer.Start();
}
private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
if (myform.pictureboxclicked)
{
myform.mytimer.Interval = 5;
myform.pictureBox1.Top = myform.counterTop;
//myform.pictureBox1.Left = myform.counterLeft;
myform.counterTop = myform.counterTop - 5;
if (myform.counterTop <-60)
{
//myform.pictureBox1.Enabled = false;
//myform.pictureBox1.Hide();
myform.pictureboxclicked = false;
myform.mytimer.Interval = myform.timerinterval;
myform.counterLeft = 415;
myform.counterTop = -60;
myform.mytimer.Stop();
}
} else {
if (myform.counterTop > 370 || myform.counterLeft < 1)
{
//myform.pictureBox1.Enabled = false;
//myform.pictureBox1.Hide();
myform.invaderlanded++;
myform.textBox2.Text = myform.invaderlanded.ToString();
myform.counterLeft = 415;
myform.counterTop = -60;
myform.pictureboxclicked = false;
myform.mytimer.Interval = myform.timerinterval;
myform.mytimer.Stop();
} else {
myform.pictureBox1.Top = myform.counterTop;
myform.pictureBox1.Left = myform.counterLeft;
myform.counterTop = myform.counterTop + 5;
myform.counterLeft = myform.counterLeft - 5;
}
}
}
}
private void button4_Click(object sender, EventArgs e)
{
Spaceship myspaceship = new Spaceship(this);
myspaceship.mspaceship();
}
答案 0 :(得分:3)
每次调用mspaceship()
时,都会向计时器添加另一个事件处理程序。
第二次单击它时,您有两个事件处理程序,每个处理程序移动5个像素。
相反,您应该只添加一次处理程序。