簡體   English   中英

c#定時器停止混亂

[英]c# Timer Stop Confusion

我想通過在單擊按鈕時更改文本顏色來將文本框文本設置為“閃爍”。

我可以讓文本按照我想要的方式閃爍,但我希望它在閃爍幾下后停止。 在計時器觸發幾次后,我不知道如何讓它停止。

這是我的代碼:

public Form1()
{
    InitializeComponent();

    Timer timer = new Timer();
    timer.Interval = 500;
    timer.Enabled = false;

    timer.Start();
    timer.Tick += new EventHandler(timer_Tick);

    if (timerint == 5)
    timer.Stop();
}

private void timer_Tick(object sender, EventArgs e)
{
    timerint += 1;

    if (textBoxInvFooter.ForeColor == SystemColors.GrayText)
        textBoxInvFooter.ForeColor = SystemColors.Highlight;
    else
        textBoxInvFooter.ForeColor = SystemColors.GrayText;
}

我知道我的問題在於我如何使用“timerint”,但我不確定把它放在哪里,或者我應該使用什么解決方案......

謝謝你的幫助!

您只需將計時器檢查放在 Tick 處理程序中。 您可以使用處理程序的sender參數訪問Timer對象。

private void timer_Tick(object sender, EventArgs e)
{
    // ...

    timerint += 1;
    if (timerint == 5)
    {
        ((Timer)sender).Stop();
    }
}

這是我用來解決您的問題的完整代碼。 它正確地停止計時器,分離事件處理程序,並處置計時器。 它在閃爍期間禁用按鈕,並在五次閃爍完成后恢復文本框的顏色。

最好的部分是它純粹是在一個 lambda 內定義的,因此不需要類級變量。

這里是:

        button1.Click += (s, e) =>
        {
            button1.Enabled = false;
            var counter = 0;
            var timer = new Timer()
            {
                Interval = 500,
                Enabled = false
            };

            EventHandler handler = null;
            handler = (s2, e2) =>
            {
                if (++counter >= 5)
                {
                    timer.Stop();
                    timer.Tick -= handler;
                    timer.Dispose();
                    textBoxInvFooter.ForeColor = SystemColors.WindowText;
                    button1.Enabled = true;
                }
                else
                {
                    textBoxInvFooter.ForeColor =
                        textBoxInvFooter.ForeColor == SystemColors.GrayText
                            ? SystemColors.Highlight 
                            : SystemColors.GrayText;
                }
            };

            timer.Tick += handler;
            timer.Start();
        };

暫無
暫無

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

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