C# WinForm线程里操作控件

做winform程序,避免不了的要在线程里控制窗体上的控件,直接在子线程里操作控件会报错“线程间操作无效,从不是创建控件***的线程访问它”。

解决方法:

private void Form1_Load(object sender, EventArgs e)
{
    Thread t1 = new Thread(t1_clock);
    t1.IsBackground = true;
    t1.Start();
}

public void t1_clock()
{
    while (true)
    {
        //保险起见,可以加上这个判断
        if (this.IsDisposed || !this.IsHandleCreated)
        {
            continue;
        }
        if (this.InvokeRequired)
        {
            this.Invoke(new Action(() =>
            {
               this.textBox1.Text = DateTime.Now.ToString("G");
             }));
        }
        Thread.Sleep(1000);
    }
}

 

posted @ 2023-04-27 09:23  xjournal  阅读(356)  评论(0编辑  收藏  举报