Home > Software engineering >  Why my timer wont work? C# i want to start Thread on pressing a key and to stops automatically
Why my timer wont work? C# i want to start Thread on pressing a key and to stops automatically

Time:03-18

Can someone tell me why this do not work? i want to start a Thread by pressing a key and stops automatically, then he have to make a rest and starts again. But if i pressing this key then nothing happens. he have to start void StartFunction, but Thread isnt starting. If i start the Thread on Forms_load then is all fine. but i need this Thread only on pressing a key

private void StartFunction()
{
    Thread AB = new Thread(SEARCHING) { IsBackground = true };
    AB.Start();

}
private void StopFunction()
{
    Thread AB = new Thread(SEARCHING) { IsBackground = true };
    AB.Abort();

}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.L)
    {
        StartFunction();
        MessageBox.Show("Timer 1 started!");

    }
}
int time = 10;
private void timer1_Tick(object sender, EventArgs e)
{
    
    time  ;
    if (time == 2 && timer1.Enabled)
    {
        timer1.Stop();
        time = 0;
        StopFunction();


    }
    if (time == 2 && !timer1.Enabled)
    {
        timer1.Start();
        time = 0;
        StartFunction();
        MessageBox.Show("Timer 1 started!");
    }
}

CodePudding user response:

You could make it easier for yourself by storing the timer_tick in a variable. When the variable has reached 120(2 min) stop the timer. First you should start the timer and then:

    private void timer1_Tick(object sender, EventArgs e)
    {
       time  ;
       if(time == 120 && timer1.Enabled)
       {
         timer1.Stop();
         time = 0;
       }
       if(time == 60 && !timer1.Enabled){
          timer1.Start();
          time = 0;
         }
    }

You can find the timer_tick event at the ptoperties of the timer.

  • Related