为了账号安全,请及时绑定邮箱和手机立即绑定

从另一个线程写入TextBox?

从另一个线程写入TextBox?

C#
萧十郎 2019-10-17 12:51:00
我无法弄清楚如何使C#Windows Form应用程序从线程写入文本框。例如在Program.cs中,我们具有绘制以下形式的标准main():static void Main(){    Application.EnableVisualStyles();    Application.SetCompatibleTextRenderingDefault(false);    Application.Run(new Form1());}然后在Form1.cs中:public Form1(){    InitializeComponent();    new Thread(SampleFunction).Start();}public static void SampleFunction(){    while(true)        WindowsFormsApplication1.Form1.ActiveForm.Text += "hi. ";}我要彻底解决这个问题吗?更新这是bendewey提供的工作代码示例:public partial class Form1 : Form{    public Form1()    {        InitializeComponent();        new Thread(SampleFunction).Start();    }    public void AppendTextBox(string value)    {        if (InvokeRequired)        {            this.Invoke(new Action<string>(AppendTextBox), new object[] {value});            return;        }        textBox1.Text += value;    }    void SampleFunction()    {        // Gets executed on a seperate thread and         // doesn't block the UI while sleeping        for(int i = 0; i<5; i++)        {            AppendTextBox("hi.  ");            Thread.Sleep(1000);        }    }}
查看完整描述

3 回答

?
蓝山帝景

TA贡献1843条经验 获得超7个赞

或者你可以喜欢


public partial class Form1 : Form

{

    public Form1()

    {

        InitializeComponent();

        new Thread( SampleFunction ).Start();

    }


    void SampleFunction()

    {

        // Gets executed on a seperate thread and 

        // doesn't block the UI while sleeping

        for ( int i = 0; i < 5; i++ )

        {

            this.Invoke( ( MethodInvoker )delegate()

            {

                textBox1.Text += "hi";

            } );

            Thread.Sleep( 1000 );

        }

    }

}


查看完整回答
反对 回复 2019-10-17
  • 3 回答
  • 0 关注
  • 553 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信