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

标签 c# winforms multithreading timer refresh

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

连接检测的功能运行良好,但是,我必须重新打开应用程序才能检测到更改。我正在寻找一种每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/

相关文章:

android - 线程安全的异步改造请求

c# - 从托管包装器重定向 native DLL stdout/stderr

c# - 使用 URL 编码的 WebApi/路由

c# - 调整窗口大小时锚定控件不会调整大小(56k 小心)

multithreading - 在线程之间发送数据的惯用方法是什么?

c# - C# 中是否有用于在给定线程上引发异常的好方法

c# - INotifyPropertyChanged 'Double' 绑定(bind)

c# - 使用 Azure SAS URL 将 Blob(所有文件)从 Azure Blob 存储下载到浏览器中

c# - 无论垂直滚动条效果如何,控件的位置

c# - 部署 C# winform 和 MySQL 项目