如何根据计时器控制更改标签颜色? [英] how do i change label color according to timer control?

查看:120
本文介绍了如何根据计时器控制更改标签颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单上有一个标签,两个按钮(启动计时器,停止计时器)和一个计时器控件.当我单击开始按钮时,标签的颜色将根据计时器而改变:1 st 第二红色,2 nd 第二蓝色,3 rd 第二个红色,第4个 蓝色等.当我单击停止"按钮时,计时器将停止,因此颜色更改也将停止.

请帮帮我.

There are one label, two buttons (start timer, stop timer) and one timer control on my form. When I click on the start button the color of the label shall change according to the timer: 1st second red color, 2nd second blue, 3rd second red, 4th blue etc.. When I click on the stop button then the timer and thus the color change shall stop.

Please help me.

推荐答案

通常的答案是使用计时器,但是在其中使用System.ComponentModel.BackgroundWorker更容易且更可靠.

顺便说一句,不要使用计时器控制(通常来说,永远不要使用),而是使用System.Timers.Timer.使用计时器很简单,您不需要任何额外的说明,只需阅读其帮助即可.您需要Control.Invoke更改颜色,请参见下文.

无论如何,如果您想使用计时器控制,它的精度不会比线程的精度要好.

这将使您了解如何使用BackgroundWorker: http://msdn.microsoft .com/en-us/library/system.componentmodel.backgroundworker.aspx [ ^ ],这-如何停止(取消)后台工作:http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/064fa2b3-8969-4060-970e-79785b854083 [ ^ ].

BackgroundWorker.DoWork中组织无限循环,在颜色变化之间使用System.Threading.Thread.Sleep(1000).通过Control.Invoke进行颜色更改.在循环中,代码应检查BackgroundWorker.CancellationPending以便支持上述参考中所述的取消机制.

就这样.

—SA
The usual answer is using timer, but there using System.ComponentModel.BackgroundWorker is much easier and more robust.

By the way, don''t use timer control (as a rule of a thumb, never), use System.Timers.Timer instead. Using the timer is simple, you won''t need any extra instruction, just read its help. You need Control.Invoke to change your colors, see below.

Anyway, if you wanted to use timer control, its accuracy would not be better then that of thread.

This will give you idea how to work with BackgroundWorker: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx[^], and this — how to stop (cancel) the background work: http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/064fa2b3-8969-4060-970e-79785b854083[^].

Organize infinite loop in BackgroundWorker.DoWork, use System.Threading.Thread.Sleep(1000) between changes in color. Do color change via Control.Invoke. In the loop, the code should check BackgroundWorker.CancellationPending in order to support cancellation mechanism described in the reference above.

That''s it.

—SA


代码为:
button_start_click()
{
    timer1.interval=timer1.interval+1000
    if timer1.interval=1000 then
        label1.backcolor=red
    elseif timer1.interval=2000 then
        label2.backcolor=green
    end if
}

button_stop()
{
    timer1.enable=false
    timer1.interval=0
}






这篇关于如何根据计时器控制更改标签颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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