如何在表单上实现闪烁标签

我有一个显示消息队列的表单,并且可以更改此消息的编号。 我真的想在增加消息数量时改变标签(队列长度),以提高forms的可用性。 我应该实现自定义控件并使用其他线程或计时器来更改标签的颜色吗? 有人实现了这么的function吗? 实现这样的行为的最佳解决方案(更少的资源和更少的性能降级)是什么?

解:

Form的组件带有计时器,可以限制每秒动画的数量,并对外部控件背景颜色实现淡出效果。

您可以创建自定义组件和事件以开始闪烁。 我认为是很好的解决方案。 闪烁你可以用计时器实现。

以下是使用asyncawait闪烁

 private async void Blink(){ while (true){ await Task.Delay(500); label1.BackColor = label1.BackColor == Color.Red ? Color.Green : Color.Red; } } 
 Timer timer = new Timer(); timer.Interval = 500; timer.Enabled = false; timer.Start(); if( messagesNum > oldMessagesNum) timer.Tick += new EventHandler( timer_Tick ); else timer.Tick -= timer_Tick; void timer_Tick( object sender, EventArgs e ) { if(messageLabel.BackColor == Color.Black) messageLabel.BackColor = Color.Red; else messageLabel.BackColor = Color.Black; } 

这是一个非常简单的实现,可以在您的表单中工作。 您还可以使用相同的代码创建自定义控件,并将Timer.Start()抛出到该控件的方法中。

我知道这是一个非常古老的post,但是任何寻找比布尔解决方案更通用的东西的人都可以从以下方面获得一些用处: 在此处输入图像描述

 using System.Diagnostics; using System.Threading.Tasks; private async void SoftBlink(Control ctrl, Color c1, Color c2, short CycleTime_ms, bool BkClr) { var sw = new Stopwatch(); sw.Start(); short halfCycle = (short)Math.Round(CycleTime_ms * 0.5); while (true) { await Task.Delay(1); var n = sw.ElapsedMilliseconds % CycleTime_ms; var per = (double)Math.Abs(n - halfCycle) / halfCycle; var red = (short)Math.Round((c2.R - c1.R) * per) + c1.R; var grn = (short)Math.Round((c2.G - c1.G) * per) + c1.G; var blw = (short)Math.Round((c2.B - c1.B) * per) + c1.B; var clr = Color.FromArgb(red, grn, blw); if (BkClr) ctrl.BackColor = clr; else ctrl.ForeColor = clr; } } 

你可以这样打电话:

 SoftBlink(lblWarning, Color.FromArgb(30, 30, 30), Color.Red,2000,false); SoftBlink(lblSoftBlink, Color.FromArgb(30, 30, 30), Color.Green, 2000,true); 

为此创建自己的UserControl ,一个inheritance自Label而不是直接从Controlinheritance的UserControl 。 添加一个StartBlinking方法,在该方法中启动一个Timer对象,其tick事件会改变标签的样式(每次更改BackgroundColor和ForegroundColor属性以创建闪烁效果)。

你也可以添加一个StopBlinking方法来关闭它,或者你可以让你的Timer在5秒后自行停止。

您可以使用动画.gif代替(也许作为数字的背景)? 它会使它看起来像旧学校的网页,但它可能会工作。

你可以在这里使用Timer类。 这是我实施的内容。 Button_click事件上的标签颜色闪烁。

 //click event on the button to change the color of the label public void buttonColor_Click(object sender, EventArgs e) { Timer timer = new Timer(); timer.Interval = 500;// Timer with 500 milliseconds timer.Enabled = false; timer.Start(); timer.Tick += new EventHandler(timer_Tick); } void timer_Tick(object sender, EventArgs e) { //label text changes from 'Not Connected' to 'Verifying' if (labelFirst.BackColor == Color.Red) { labelFirst.BackColor = Color.Green; labelFirst.Text = "Verifying"; } //label text changes from 'Verifying' to 'Connected' else if (labelFirst.BackColor == Color.Green) { labelFirst.BackColor = Color.Green; labelFirst.Text = "Connected"; } //initial Condition (will execute) else { labelFirst.BackColor = Color.Red; labelFirst.Text = "Not Connected"; } }