2012-05-18 11 views
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(); 
     } 
    } 
} 
+2

你到目前爲止試過的是什麼? –

+2

你有什麼嘗試?看看[timer](http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx)類。特別是Elapsed事件可能會引起你的興趣。 – Skalli

+0

我試過這個..但它沒有工作。見上面的代碼。 – annayak

回答

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()方法開始經過指定的時間段後,它會觸發。

+0

我不確定解釋代碼是否會有助於更好地提供一個完整的源代碼示例,而不需要任何評論。 – Skalli

+0

謝謝)我正在嘗試它 – annayak

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"; 
    } 
} 
+0

而不是使用變量來保持關鍵狀態的按下,使用KeyPress事件可能是一個更好的選擇。 – Skalli

+0

謝謝)你的變體作品。 – annayak

+0

@Skalli'KeyPress'也會繼續發射。 – LarsTech