2012-12-18 115 views
1

我有一个Timer1的窗体,它设置为10Sec。如何捕获等待用户输入的时间间隔?

有一个KeyDown事件 - 当用户按下“Enter”时,我想在“ans”中保存10s间隔前的持续时间。

例如:如果我现在开始定时器1和3秒后,我按Enter键,ANS = 3,如果我没有按任意键,ANS将等于10。

我有这样的代码:

if (e.KeyCode == Keys.Enter) 
    { 
     ResponseTimeList.Add(timer1.Interval); 
    } 

* ResponseTimeList是:

public List<double> ResponseTimeList = new List<double>(); 

我怎么能提高呢?

谢谢。

回答

4

那么,从一开始,Timer就不是你想要使用的。定时器类被设计为在预定义的时间间隔内触发事件;例如,您可以使用计时器每10秒更新一次表单上的文本框。

相反,你想要做的是使用秒表(System.Diagnostics.Stopwatch)。打电话Stopwatch.Start(),只要你想开始计时。当用户按下输入时,只需调用Stopwatch.Stop(),然后获取以秒为单位的时间间隔。

最后,对于10秒的逻辑,你将需要使用像这样(有条件的评价):

var timeToDisplay = Stopwatch.ElapsedMilliseconds > 10000 ? 10 : Stopwatch.ElapsedMilliseconds/1000 
+0

明白了!谢谢。 –

0

您可以使用定时器事件。

bool isPressed = false; 
Timer timer1 = new Timer() { Interval = 10000}; 

timer1.Tick += (s, e) => 
{ 
    if (!isPressed) 
     ResponseTimeList.Add(timer1.Interval); 

    isPressed = false; 
}; 

当按下键:

if (e.KeyCode == Keys.Enter) 
{ 
    ResponseTimeList.Add(timer1.Interval); 
    isPressed = true; 
}