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 Answers2

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();
}
Jarek Danielak
  • 394
  • 4
  • 18
  • 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... – Van Minh Nhon TRUONG May 07 '20 at 10:56
  • That's correct. Then things get a little more complicated and you have to register a global hotkey like in [this](http://www.pinvoke.net/default.aspx/user32/registerhotkey.html) article. And [here](https://stackoverflow.com/questions/11377977/global-hotkeys-in-wpf-working-from-every-window) is some question related to WinForms directly. – Jarek Danielak May 07 '20 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! – Van Minh Nhon TRUONG May 08 '20 at 17:00
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,696
  • 3
  • 12
  • 37