c#定时器停止混乱 [英] c# Timer Stop Confusion

查看:63
本文介绍了c#定时器停止混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过在单击按钮时更改文本颜色来将文本框文本设置为闪烁".

I would like to set a textbox text to "blink" by changing text colors when a button is clicked.

我可以让文本按照我想要的方式闪烁,但我希望它在闪烁几次后停止.定时器触发几次后,我不知道如何让它停止.

I can get the text to blink how I want it to, but I want it to stop after a few blinks. I cannot figure out how to make it stop after the timer fires a few times.

这是我的代码:

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",但我不确定把它放在哪里,或者我应该使用什么解决方案......

I know my problem lies with how I'm using the "timerint", but I'm not sure where to put it, or what solution I should use...

感谢您的帮助!

推荐答案

这是我用来解决您的问题的完整代码.它正确地停止计时器,分离事件处理程序,并处置计时器.它在闪烁期间禁用按钮,并在五次闪烁完成后恢复文本框的颜色.

Here's the complete code that I would use to solve your issue. It correctly stops the timer, detaches the event handler, and disposes the timer. It disables the button during the flashing, and also restores the colour of the textbox after the five flashes are complete.

最好的部分是它纯粹是在一个 lambda 内定义的,因此不需要类级变量.

The best part is that it is purely defined within the one lambda, so no class-level variables required.

这是:

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

这篇关于c#定时器停止混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆