0

我有四个按钮,称为“ship1,ship2”等。我希望它们移动到表单的右侧(以相同的速度并同时开始),每次单击一个“ship”时,所有的船都应该停下来。

我知道我需要使用计时器(我编写了使用线程的代码,但是在停止船只时给我带来了麻烦。)我不知道如何使用计时器。

我试图阅读 MDSN 中的计时器信息,但我不明白。所以你可以帮助我吗?

这里是使用线程的代码。 我不想用它。我需要使用定时器!(我在这里发布它是因为它没有让我在没有任何代码的情况下发布

    private bool flag = false;
    Thread thr;
    public Form1()
    {
        InitializeComponent();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        flag = false;
        thr = new Thread(Go);
        thr.Start();

    }

    private delegate void moveBd(Button btn);

    void moveButton(Button btn)
    {
        int x = btn.Location.X;
        int y = btn.Location.Y;
        btn.Location = new Point(x + 1, y);
    }

    private void Go()
    {
        while (((ship1.Location.X + ship1.Size.Width) < this.Size.Width)&&(flag==false))
        {
            Invoke(new moveBd(moveButton), ship1);
            Thread.Sleep(10);
        }

        MessageBox.Show("U LOOSE");

    }

    private void button1_Click(object sender, EventArgs e)
    {
        flag = true;
    }
4

1 回答 1

1

你用谷歌搜索过Windows.Forms.Timer吗?

您可以通过以下方式启动计时器:

Timer timer = new Timer();

timer.Interval = 1000; //one second
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Enabled = true;
timer.Start();

您需要一个事件处理程序来处理Elapsed事件,您将在其中放置代码来处理移动“按钮”:

private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)  
{
      MoveButton();       
}
于 2012-08-02T15:33:18.890 回答