如何使用键盘事件和计时器

本文关键字:计时器 事件 键盘 何使用 | 更新日期: 2023-09-27 18:34:46

我想要下一个:当您按空格键 - 标签 1 时。文本变为"向上",几秒钟后(从 1 到 5 随机(标签1。文本将更改为"移开手",然后更改为 KeyUp 标签 1。文本将更改为"向下"。我知道如何使用 KeyUp 和 KeyDown,但我不明白如何使用计时器???

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private Timer timer = new Timer();
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
            {
                label1.Text = "Down";
                timer.Interval = 5000;//5 seconds
                timer.Tick += new EventHandler(timer1_Tick);
                timer.Start();
            }
        }
        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
            {
                label1.Text = "Up";
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            label1.Text = "Remove";
            timer.Stop();
        }
    }
}

如何使用键盘事件和计时器

未测试,但像这样:

    private Timer timer = new Timer();
    private void OnKeyPress(object sender, KeyPressEventArgs e)
    {
        //check key press args for space here
        timer.Interval = 5000;//5 seconds
        timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
        timer.Start();
    }
    private void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        label1.Text = "Up";
        timer.Elapsed -= timer_Elapsed;
        timer.Stop();
    }

基本上,interval 属性以毫秒为单位,您可以在此处指定要等待的时间。然后,将事件处理程序添加到 Elapsed 事件。当从调用 Start(( 方法开始经过指定的时间段时,这将触发。

如果用户不松手,KeyDown将继续触发,因此您可能只需要一个变量来启动计时器一次。

private Random rnd = new Random();
private bool _SpacePressed = false;
public Form1() {
  InitializeComponent();
  this.KeyPreview = true;
  label1.Text = "Down";
  timer1.Tick += new EventHandler(timer1_Tick);    
}
void timer1_Tick(object sender, EventArgs e) {
  timer1.Stop();
  label1.Text = "Remove Hand";
}
protected override void OnKeyDown(KeyEventArgs e) {
  base.OnKeyDown(e);
  if (e.KeyCode == Keys.Space && !_SpacePressed) {
    _SpacePressed = true;
    label1.Text = "Up";
    timer1.Interval = rnd.Next(1, 5) * 1000;
    timer1.Start();
  }
}
protected override void OnKeyUp(KeyEventArgs e) {
  base.OnKeyUp(e);
  if (_SpacePressed) {
    _SpacePressed = false;
    timer1.Stop();
    label1.Text = "Down";
  }
}