如何使用键盘上的快捷键在Windows Forms中停止计时器?

问题描述 投票:0回答:1

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

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

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

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

!!! “名称键盘在当前上下文中不存在”

c# winforms timer visual-studio-2017 keyboard
1个回答
0
投票

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

the documentation中了解更多。

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

void OnKeyPress(object sender, KeyPressEventArgs e)
{
    if (myTimer.Enabled)
         myTimer.Stop();
}
© www.soinside.com 2019 - 2024. All rights reserved.