gpt4 book ai didi

c# - 文本框的计时器/刷新功能

转载 作者:太空宇宙 更新时间:2023-11-03 18:12:32 27 4
gpt4 key购买 nike

在我的应用程序中,我有两个带有两个标签的文本框:“已连接”和“未连接”。从我的代码中可以看到,如果建立了连接,则“已连接”文本框将充满绿色,表示网络连接。如果不是,它将为红色。

连接检测的功能运行良好,但是,我必须重新打开应用程序才能检测到更改。我正在寻找一种每5-10秒左右刷新一次应用程序以自动检测连接性变化的方法。我不想清除任何其他字段或框的内容,而仅清除彩色文本框。可以说是一个软轮询循环。我将如何使用Timer方法执行此操作。我应该创建一个新的线程来运行计时器并刷新该框吗?

谢谢。

  if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == false)
{
noConnect.Select(); //if not connected, turn box red
noConnect.BackColor = Color.Red;

}

else
{
netConnect.Select(); // if connected, turn box green
netConnect.BackColor = Color.Lime;

}

//need to refresh box/application without losing other box/field contents
//in order to constantly check connectivity around 5-10 seconds or so
//constantly check connectivity

最佳答案

这样的事情会起作用

    public Form1()
{
InitializeComponent();
var timer = new Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = 10000; //10 seconds
timer.Start();
}

void timer_Tick(object sender, EventArgs e)
{
if (your_function_call())
{
netConnect.BackColor = Color.Green;
}
else
netConnect.BackColor = Color.Red;
}

在每个时间间隔都会重复调用timer_Tick,您可以轮询状态并更新控件。由于在UI线程中调用了计时器回调,因此您可以更新任何UI元素。

Timer Class

A Timer is used to raise an event at user-defined intervals. This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. It requires that the user code have a UI message pump available and always operate from the same thread, or marshal the call onto another thread. When you use this timer, use the Tick event to perform a polling operation or to display a splash screen for a specified period of time. Whenever the Enabled property is set to true and the Interval property is greater than zero, the Tick event is raised at intervals based on the Interval property setting.



此解决方案使用 System.Windows.Forms.Timer在UI线程上调用滴答声。如果使用 System.Timers.Timer,则回调将不在UI线程上。

关于c# - 文本框的计时器/刷新功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11952075/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com