如何使用键盘事件停止 Windows 表单中的计时器?

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

我想通过按键盘上的任意键来停止 运行 在我的 Windows 表单中的计时器。 你有什么想法吗?

例如,在我的表单中,我正在尝试这样做:

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

问题是即使我已经添加了程序集PresentationCore.dll,但是无法识别上面代码中的Keyboard。我正面临这个错误:

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

您可以在窗体的构造函数中添加 KeyPressEventHandler 并在此处理程序中停止计时器。此代码假定 myTimer 可在 OnKeyPress 中访问,例如是这个表单的私有字段。

the documentation 阅读更多内容。

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

void OnKeyPress(object sender, KeyPressEventArgs e)
{
    if (myTimer.Enabled)
         myTimer.Stop();
}

您还需要添加引用 WindowsBase.dll

并在计时器处理程序中检查它。

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;
}