0

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"

2
  • Your question should be how to listen for keyboard events, this is most definitely a duplicate
    – TheGeneral
    May 6, 2020 at 23:50
  • @MichaelRandall I have changed the title. thanks :) May 7, 2020 at 11:20

2 Answers 2

1

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;
}
3
  • Still having this error: the type or namespace name keyboard does not exist in the namespace 'System.Windows.Input' May 7, 2020 at 11:12
  • @VanMinhNhonTRUONG I added the reference WindowsBase and PresentationCore , and it works fine on several machines. Did you add them by steps Project => Add Reference...? May 8, 2020 at 1:23
  • 1
    @VanMinhNhonTRUONG Ought to be PresentationCore, rather than System.Windows.Presentation. May 11, 2020 at 1:14
1

You can add KeyPressEventHandler in your Form's constructor and stop the timer in this handler. This code assumes myTimer is accessible in OnKeyPress e.g. is a private field of this Form.

Read more in the documentation.

public MyForm
{
    this.KeyPress += new KeyPressEventHandler(OnKeyPress);
}

void OnKeyPress(object sender, KeyPressEventArgs e)
{
    if (myTimer.Enabled)
         myTimer.Stop();
}
3
  • thanks so much for your answer. But if my form is not the first app displayed on the desktop, this does not work because we do not press the key on the form... May 7, 2020 at 10:56
  • That's correct. Then things get a little more complicated and you have to register a global hotkey like in this article. And here is some question related to WinForms directly. May 7, 2020 at 12:03
  • Ya it seems more quite complicated... I'm trying another method to do this (e.g. by using another timer). thanks so much! May 8, 2020 at 17:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.