Ssasidhar
Ssasidhar

Reputation: 485

How to stop the timer in click event ? In C#.Net?

How do you stop the Winforms timer firing Tick event?

this is my code:

    Timer tm = new Timer();

    private void button1_Click(object sender, EventArgs e)
    {
        tm = new Timer();
        tm.Interval = 1000;
        tm.Tick += new EventHandler(tm_Tick);
        tm.Start();
    }

    void tm_Tick(object sender, EventArgs e)
    {
        MessageBox.Show("hi");
        tm.Stop();

    }

Upvotes: 2

Views: 6900

Answers (1)

DeadDog
DeadDog

Reputation: 241

I am unsure of what you are trying to do. Are you trying to make the tick event handler only execute once? If that is the case, your current setup will only stop the timer from firing tick events when the first message box is closed. To avoid this problem, switch the two lines in your tm_Tick method.

Also, you shouldn't set up the Timer in the click handler. You should only start it. I suggest you to do something in the lines of this:

Timer tm;
private void form1_Load(object sender, EventArgs e)
{
    tm = new Timer();
    tm.Interval = 1000;
    tm.Tick += new EventHandler(tm_Tick);
}
private void button1_Click(object sender, EventArgs e)
{
    tm.Start();
}

void tm_Tick(object sender, EventArgs e)
{
    tm.Stop();
    MessageBox.Show("hi");
}

Upvotes: 5

Related Questions