2012-08-02 46 views
0

我有四个按钮被称为“ship1,ship2”等。 我希望他们移动到窗体的右侧(以相同的速度和同时开始),并且每次我点击一个“船”时,所有的船只都应该停下来。我知道我需要使用一个计时器(我已经编写了使用线程的代码,但是在停止船只时它给了我麻烦)。我不知道如何使用计时器。我不知道如何使用计时器。我不知道如何使用计时器。我不知道如何使用计时器。使用定时器移动按钮

我试图读取MDSN中的定时器信息,但我不理解它。 那么你能帮助我吗?

HERES使用线程的代码。 我不想使用它。我需要使用定时器! (我张贴在这里,因为它不给我后,没有任何代码

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; 
    } 
+1

这似乎是作业\分配。如果是,我会更新你的标签。 – zeencat 2012-08-02 15:30:12

+0

哇。你不能点击这样的按钮。您正在阻止作为UI线程的主线程。使用[timer](http://msdn.microsoft.com/en-us/library/system.timers.timer(v = vs.71).aspx)与已用事件。问题在于,除非你有一个很短的'Interval',比如0.04秒(25 FPS),否则你不会得到流畅的运动。如果您正在制作游戏,请查看[XNA](http://www.xnadevelopment.com/index.shtml) – musefan 2012-08-02 15:37:16

+0

@ zeencat它不是。我正在尝试构建一款游戏。 – Noam650 2012-08-02 16:10:58

回答

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();  
} 
+0

System.Windows.Forms.Timer将是一个更好的选择,否则在Timer_Elapsed事件中检查InvokeRequired几乎是不可避免的,以避免交叉线程异常。否则同意。 – dash 2012-08-02 15:39:47

+0

好点!将编辑 – dtsg 2012-08-02 15:46:27

+0

@Duane,当我想让它停止移动时,我该如何停止时钟? – Noam650 2012-08-02 16:12:25