我有一个控制台应用程序,它在单独的线程中启动Windows窗体,如下所示:
static void Main(string[] args)
{
Thread t = new Thread(StartForm);
t.Start();
}
static public void StartForm()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
- 表单包含富文本框控件。
我的问题:如何将文本写入我的应用程序(和 anyThread)中的表单中的富文本框控件?
PS:我还需要控制台留下来。
Invoke
从后台线程将文本写入RichTextBox
。
在 Form1 设计器中,将richTextBox1.Modifiers
更改为 public
,以便从其他线程访问它。
static void Main(string[] args)
{
Thread t = new Thread(StartForm);
t.Start();
string text = Console.ReadLine();
form.UIThread(() => form.richTextBox1.Text += text);
Console.ReadLine();
}
public static Form1 form;
public static void StartForm()
{
form = new Form1();
Application.EnableVisualStyles();
Application.Run(form);
}
public static void UIThread(this Control control, Action action)
{
if (control.InvokeRequired) // You're access from other thread
{
control.BeginInvoke(action); // Invoke to access UI element
}
else
{
action.Invoke();
}
}
如果要从另一个线程更新表单的内容,则需要使用 Invoke
或 BeginInvoke
。您可以通过检查 InvokeRequired
属性来检查是否需要这样做。虽然可以传递任何Delegate
,但应传递MethodInvoker
委托,该委托是为与 Windows 窗体一起使用而设置的特殊委托。
例如:
if(form.TheRichTextBox.InvokeRequired)
{
form.TheRichTextBox.Invoke(new MethodInvoker(() =>
{
form.TheRichTextBox.Text += "I had to be invoked!";
}));
}
else
{
form.TheRichTextBox.Text += "I didn't have to be invoked!";
}