猿问

从另一个线程写入TextBox?

我无法弄清楚如何使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);

        }

    }

}


萧十郎
浏览 585回答 3
3回答

蓝山帝景

或者你可以喜欢public partial class Form1 : Form{&nbsp; &nbsp; public Form1()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; InitializeComponent();&nbsp; &nbsp; &nbsp; &nbsp; new Thread( SampleFunction ).Start();&nbsp; &nbsp; }&nbsp; &nbsp; void SampleFunction()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // Gets executed on a seperate thread and&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // doesn't block the UI while sleeping&nbsp; &nbsp; &nbsp; &nbsp; for ( int i = 0; i < 5; i++ )&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.Invoke( ( MethodInvoker )delegate()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; textBox1.Text += "hi";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } );&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Thread.Sleep( 1000 );&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答