簡體   English   中英

我如何才能在實時C#中以秒為單位停止計時器?

[英]How I can stop a timer with seconds in real time c#?

我正在嘗試在經過實時16秒后停止計時器,但是我不知道該怎么做。

我舉了一個小例子:當picturebox1與picturebox2相交時,此動作將激活一個計時器,並且該計時器必須在16秒鍾內實時顯示picturebox3,並在將其停止(計時器)后顯示(而picturebox3不顯示)。

(對不起,我的英語。但是西班牙語的StackOverflow信息不多)。

我正在使用Windows窗體和C#

    private void timer2_Tick(object sender, EventArgs e)
    {
        pictureBox7.Hide();
        if ((pictureBox3.Bounds.IntersectsWith(pictureBox2.Bounds) && pictureBox2.Visible) || (pictureBox5.Bounds.IntersectsWith(pictureBox2.Bounds) && pictureBox2.Visible))
        {                
            puntaje++;
            this.Text = "Puntaje: " + puntaje;
            if (puntaje % 5 == 0)
            {
               timer3.Enabled=true;
 //This is the part where i want set down the timer3, timer 2 is on

            }
        }

您可以在計時器滴答事件處理程序上嘗試執行此操作。 時間跨度計算兩個日期之間經過的時間。 在這種情況下,自16秒鍾以來,我們將其計為負數。

private void timer1_Tick(object sender, EventArgs e)
    {
        TimeSpan ts = dtStart.Subtract(DateTime.Now);
        if (ts.TotalSeconds <= -16)
        {
            timer1.Stop();
        }
    }

確保在啟動計時器時聲明了dtStart(DateTime):

timer1.Start();
dtStart = DateTime.Now;

我可以看到的最干凈的方法是使用System.Timers.Timer的interval參數。

這是代碼示例

var timer = new Timer(TimeSpan.FromSeconds(16).TotalMilliseconds) { AutoReset = false };
timer.Elapsed += (sender, e) =>
{
    Console.WriteLine($"Finished at exactly {timer.Interval} milliseconds");
};
_timer.Start();

TimeSpan.FromSeconds(16).TotalMilliseconds基本上可以轉換為16000,但是我使用TimeSpan靜態方法讓您更容易理解它,並使其更具可讀性。

計時器的AutoReset屬性告訴它僅應觸發一次。

根據您的代碼進行了調整

private void timer2_Tick(object sender, EventArgs e)
{
    pictureBox7.Hide();
    if ((pictureBox3.Bounds.IntersectsWith(pictureBox2.Bounds) && pictureBox2.Visible) 
        || (pictureBox5.Bounds.IntersectsWith(pictureBox2.Bounds) && pictureBox2.Visible))
    {                
        puntaje++;
        this.Text = "Puntaje: " + puntaje;
        if (puntaje % 5 == 0)
        {
            var timer3 = new Timer(TimeSpan.FromSeconds(16).TotalMilliseconds) { AutoReset = false };
            timer3.Elapsed += (sender, e) =>
            {
                pictureBox3.Visible = true;
            };
            timer3.Start();
        }
    }
}

如果可以解決您的問題,請標記為已回答問題。

暫無
暫無

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

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