从另一个线程写入文本框? [英] Writing to a TextBox from another thread?
问题描述
我不知道如何让 C# Windows 窗体应用程序从线程写入文本框.例如在 Program.cs 中,我们有绘制表单的标准 main():
I cannot figure out how to make a C# Windows Form application write to a textbox from a thread. For example in the Program.cs we have the standard main() that draws the form:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
然后我们在 Form1.cs 中有:
Then we have in the Form1.cs:
public Form1()
{
InitializeComponent();
new Thread(SampleFunction).Start();
}
public static void SampleFunction()
{
while(true)
WindowsFormsApplication1.Form1.ActiveForm.Text += "hi. ";
}
我是不是完全错了?
更新
这是本德威提供的工作代码示例:
Here is the working code sample provided from 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);
}
}
}
推荐答案
在你的 MainForm 上创建一个函数来设置文本框,检查 InvokeRequired
On your MainForm make a function to set the textbox the checks the InvokeRequired
public void AppendTextBox(string value)
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(AppendTextBox), new object[] {value});
return;
}
ActiveForm.Text += value;
}
虽然在你的静态方法中你不能只是调用.
although in your static method you can't just call.
WindowsFormsApplication1.Form1.AppendTextBox("hi. ");
你必须在某处有一个对 Form1 的静态引用,但这并不是真正推荐或必要的,你能不能让你的 SampleFunction 不是静态的,如果是这样你就可以调用
you have to have a static reference to the Form1 somewhere, but this isn't really recommended or necessary, can you just make your SampleFunction not static if so then you can just call
AppendTextBox("hi. ");
它将附加到不同的线程上,并在需要时使用 Invoke 调用编组到 UI.
It will append on a differnt thread and get marshalled to the UI using the Invoke call if required.
完整示例
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);
}
}
}
这篇关于从另一个线程写入文本框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!