我无法弄清楚如何使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 );
}
}
}
- 3 回答
- 0 关注
- 584 浏览
添加回答
举报
0/150
提交
取消