0

我想要下一个:当你按空格键时 - label1.Text 变为“向上”,几秒钟后(从 1 到 5 随机)label1.Text 将变为“移除手”,然后 KeyUp label1.Text 将变为“向下” . 我知道如何使用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();
        }
    }
}
4

2 回答 2

1

未经测试,但类似这样:

    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() 方法后经过指定的时间段后触发。

于 2012-05-18T14:11:24.163 回答
0

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";
  }
}
于 2012-05-18T14:45:02.647 回答