zoukankan      html  css  js  c++  java
  • Winform Timer用法,Invoke在Timer的事件中更新控件状态

    System.Timers.Timer可以定时执行方法,在指定的时间间隔之后执行事件。

    form窗体上放一个菜单,用于开始或者结束定时器Timer。

    一个文本框,显示定时执行方法。

    public partial class Form1 : Form
        {
            int count = 0;
            System.Timers.Timer timer;
            public Form1()
            {
                InitializeComponent();
    
                timer = new System.Timers.Timer();
                timer.Interval = 1000 * 5;
                timer.Elapsed += (x, y) =>
                {
                    count++;
    
                    InvokeMethod(string.Format("{0} count:{1}", DateTime.Now.ToString("HH:mm:ss"), count));
                };
            }
    
            private void InvokeMethod(string txt)
            {
                Action<string> invokeAction = new Action<string>(InvokeMethod);
                if (this.InvokeRequired)
                {
                    this.Invoke(invokeAction, txt);
                }
                else
                {
                    txtLog.Text += txt + Environment.NewLine;
                }
            }
    
            private void StartMenuItem_Click(object sender, EventArgs e)
            {
                if (StartMenuItem.Text == "开始")
                {
                    txtLog.Text += string.Format("{0} {1}{2}", DateTime.Now.ToString("HH:mm:ss"),
                    "开始运行...", Environment.NewLine);
                    timer.Start();
                    StartMenuItem.Text = "结束";
                }
                else
                {
                    txtLog.Text += string.Format("{0} {1}{2}", DateTime.Now.ToString("HH:mm:ss"),
                    "结束运行...", Environment.NewLine);
                    timer.Stop();
                    StartMenuItem.Text = "开始";
                }
            }
        }

    运行截图如下:

    Timer事件中更新窗体中文本框的内容,直接使用txtLog.Text +=...方式,会报异常“线程间操作无效: 从不是创建控件“txtLog”的线程访问它。”

    因此用到了Invoke方法,这个方法用于“在拥有控件的基础窗口句柄的线程上,用指定的参数列表执行指定委托”。

    解释一下,就是说文本框控件是在主线程上创建的,使用Invoke方法委托主线程更改文本框的内容。

  • 相关阅读:
    《临江仙·滚滚长江东逝水》
    .net Core Newtonsoft.Json 解析巨坑之注释影响代码
    C# 后端post请求帮助类
    鼠标点击事件
    常用Windows 消息列表
    WinUser.h>>>OnMessage事件
    Jellyfin流媒体服务器搭建和一些小坑
    ios开发遇到的问题
    节省你的时间,用AHK实现随机打开文件
    一些简单的AHK脚本提升电脑使用体验
  • 原文地址:https://www.cnblogs.com/tanpeng/p/7073879.html
Copyright © 2011-2022 走看看