gpt4 book ai didi

c# - 在 C# 中闪烁标签 backColor

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:57 31 4
gpt4 key购买 nike

我有一个包含 4 个标签的表单。我希望这些标签以指定的频率闪烁,例如 12.5、10、8 和 4 HZ。我使用了计时器,但它无法正常工作,它们闪烁的频率要低得多,我知道这是因为下面的 freqMethod 中嵌套了 if。我该如何解决这个问题?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Timers;
using System.Threading;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
System.Timers.Timer mainTimer;
private int counter = 0;
Color lColor = Color.FromArgb(255, 192, 128);
bool buttonPressed = false;

public Form1()
{

InitializeComponent();
label1.BackColor = lColor;
label2.BackColor = lColor;
label3.BackColor = lColor;
label4.BackColor = lColor;
mainTimer = new System.Timers.Timer(1);
mainTimer.Elapsed += new ElapsedEventHandler(timerElapsed);
}


private void button2_Click(object sender, EventArgs e)
{
if (buttonPressed)
{
mainTimer.Enabled = false;
buttonPressed = !buttonPressed;
counter = 0;
}
else
{

mainTimer.Enabled = true;
buttonPressed = !buttonPressed;
counter = 0;
}
}

//Frequency Method

public void freqMethod()
{
if (counter % 80 == 0)
if (label4.backColor == lColor)
label4.backColor = Color.black;
else
label4.backColor = lColor;
if (counter % 100 == 0)
if (label3.backColor == lColor)
label3.backColor = Color.black;
else
label3.backColor = lColor;
if (counter % 125 == 0)
if (label2.backColor == lColor)
label2.backColor = Color.black;
else
label2.backColor = lColor;
if (counter % 250 == 0)
if (label1.backColor == lColor)
label1.backColor = Color.black;
else
label1.backColor = lColor;



}
private void timerElapsed(object source, ElapsedEventArgs e) {
counter++;
freqMethod();
}

}
}

最佳答案

给定以下值(如果您想使用一个计时器同步它们),它们可以具有的公共(public)间隔是 5 毫秒。所以你需要每 5ms 勾选定时器并检查频率。但请注意使用计时器,如下所述:

12.5hz = 80ms
10hz = 100ms
8hz = 125ms
4hz = 250ms

来自 MSDN 使用 System.Timers.Timer 的备注 ( https://msdn.microsoft.com/en-us/library/system.timers.timer.interval(v=vs.110).aspx ) 请参阅备注部分。

You use the Interval property to determine the frequency at which the Elapsed event is fired. Because the Timer class depends on the system clock, it has the same resolution as the system clock. This means that the Elapsed event will fire at an interval defined by the resolution of the system clock if the Interval property is less than the resolution of the system clock. The following example sets the Interval property to 5 milliseconds. When run on a Windows 7 system whose system clock has a resolution of approximately 15 milliseconds, the event fires approximately every 15 milliseconds rather than every 5 milliseconds

但是如果你可以为每个计时器使用多个计时器,那么你可以像 Yeldar 提到的那样设置计时器的每个间隔。

关于c# - 在 C# 中闪烁标签 backColor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31470968/

31 4 0