如何使用键盘事件来停止Windows窗体中的定时器?

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

我想通过按下键盘上的任何一个键来停止一个正在运行的定时器,你有什么办法吗?

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

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

问题是,即使我已经添加了程序集。PresentationCore.dll 不过 键盘 在上面的代码中没有被识别。而我正面临这个错误。

!!! "当前上下文中的键盘名称不存在"

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

你还需要添加引用 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;
}

1
投票

你可以在Form的构造函数中添加KeyPressEventHandler,并在该处理程序中停止定时器。这段代码假设 myTimer 在OnKeyPress中是可以访问的,例如,是这个表格的一个私人领域。

阅读更多信息 文件.

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.