我想通过按键盘上的任意键来停止在Windows窗体中运行的计时器。你有什么主意吗?
例如,在我的表单中,我正在尝试这个:
myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Interval = 400;
if (Keyboard.IsKeyDown(Key.Enter))
{
if (myTimer.Enabled)
myTimer.Stop();
}
问题甚至是我已经添加了程序集PresentationCore.dll,但是无法识别以上代码中的Keyboard。我正面临这个错误:
!!! “名称键盘在当前上下文中不存在”
您可以在窗体的构造函数中添加KeyPressEventHandler并在此处理程序中停止计时器。此代码假设在OnKeyPress中可以访问myTimer
,例如是此表单的私有字段。
在the documentation中了解更多。
public MyForm
{
this.KeyPress += new KeyPressEventHandler(OnKeyPress);
}
void OnKeyPress(object sender, KeyPressEventArgs e)
{
if (myTimer.Enabled)
myTimer.Stop();
}