Noam650
Noam650

Reputation: 113

moving a button using a timer

I have four buttons that are called "ship1,ship2" etc. I want them to move to the right side of the form (at the same speed and starting at the same time), and every time I click in one "ship", all the ships should stop.

I know that I need to use a timer (I have the code written that uses threading, but it gives me troubles when stopping the ships.) I don't know how to use timers.

I tried to read the timer info in MDSN but I didn't understand it. So u can help me?

HERES the code using threading. I don't want to use it. I need to use a TIMER! (I posted it here because it doesnt give me to post without any code

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

Upvotes: 0

Views: 4366

Answers (1)

dtsg
dtsg

Reputation: 4468

Have you googled Windows.Forms.Timer?

You can start a timer via:

Timer timer = new Timer();

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

You'll need an event handler to handle the Elapsed event which is where you'll put the code to handle moving the 'Button':

private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)  
{
      MoveButton();       
}

Upvotes: 1

Related Questions