Search code examples
c#winformstimervisual-studio-2017keyboard

How to use Keyboard events to stop a Timer in Windows Forms?


I want to stop a timer which is running in my Windows Form by pressing any key from the keyboard. Do you have any idea ?

For example, inside my Form, I am trying this :

myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Interval = 400;
if (Keyboard.IsKeyDown(Key.Enter))
{
    if (myTimer.Enabled)
         myTimer.Stop();
}

The problem is even I have already added the assembly PresentationCore.dll but Keyboard in the code above is not recognized. And I'am facing this error:

!!! "the name keyboard does not exist in the current context"


Solution

  • You also need to add the reference WindowsBase.dll.

    And check it in timer handler.

    int i = 0;
    private void timer1_Tick(object sender, EventArgs e)
    {
        Console.WriteLine(i++);
    
        if (System.Windows.Input.Keyboard.IsKeyDown(System.Windows.Input.Key.Enter))
        {
            timer1.Enabled = false;
            MessageBox.Show("Timer Stopped");
        }
    }
    
    private void Form1_Load(object sender, EventArgs e)
    {
        timer1.Enabled = true;
    }