簡體   English   中英

如何在等待用戶輸入時捕獲時間間隔?

[英]How to capture a time interval while waiting for user input?

我有一個帶有Timer1的Form,它設置為10Sec。

有一個KeyDown事件 - 當用戶按下“Enter”時,我想在“ans”中保存在10S間隔結束之前的持續時間。

例如:如果我現在啟動timer1,並且在3Sec之后,我按Enter鍵,ans = 3.如果我沒有按任何鍵,則ans將等於10。

我有這個代碼:

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

* ResponseTimeList是:

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

我怎樣才能改善它?

謝謝。

好吧,首先,Timer不是你想要使用的。 計時器類旨在以預定義的時間間隔觸發事件; 例如,您可以使用計時器每10秒更新一次表單上的文本框。

相反,你想要做的是使用秒表(System.Diagnostics.Stopwatch)。 無論何時想要開始計時,都要調用Stopwatch.Start()。 當用戶按Enter鍵時,只需調用Stopwatch.Stop()然后獲取已經過的時間間隔(以秒為單位)。

最后,對於10秒邏輯,您需要使用類似的東西(條件評估):

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

您可以使用Timer的Tick事件。

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM