在 Application.Run() 之后更新表单 [英] Update a form after Application.Run()
问题描述
这是我想要做的
// pseudo code
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 myForm = new Form1();
Application.Run(myForm);
while(true)
{
string a = readline();
}
form1.show(a)
换句话说,我需要表单总是显示输入.但上面的代码将在Application.Run(myForm);"之后停止.我不在 form1 类中编写此类代码的原因是代码的主要部分运行在用 F# 编写的机器学习引擎上,并且因为 F# 没有好的视觉设计器.所以我试图创建一个简单的 form1.dll,并使用它来绘制随时间变化的结果.所以我的问题是我只能初始化表单,但我不能随着时间的推移更新它.任何提示将不胜感激.
In other words , I need the form always show the input. but the code above will stop after 'Application.Run(myForm);'. The reason I don't write such code in the form1 class is the main part of code is run on a machine learning engine written in F#, and because F# doesn't have a good visual designer. So I am trying to create a simple form1.dll, and use it to plot the result over time. So my problem is I only can initialise the form, but I can't update it over time. Any hints will be appreciated.
推荐答案
您正在尝试同时做两件事,因此您的应用程序应该通过使用 2 个线程来反映这一点.接下来,Form的Show()方法不接受字符串,所以需要自己实现方法.
You're trying to do 2 things at the same time, so your application should reflect that by using 2 threads. Next, the Form's Show() method does not accept a string, so you need to implement your own method.
这是一个 C# 2.0 WinForms 解决方案.程序运行线程并处理控制台输入:
Here's a C# 2.0 WinForms solution. The program runs the thread and processes the console input:
static class Program
{
[STAThread]
private static void Main()
{
// Run form in separate thread
var runner = new FormRunner();
var thread = new Thread(runner.Start) {IsBackground = false};
thread.Start();
// Process console input
while (true)
{
string a = Console.ReadLine();
runner.Display(a);
if (a.Equals("exit")) break;
}
runner.Stop();
}
}
FormRunner 负责线程调用:
The FormRunner takes care about thread invocation:
internal class FormRunner
{
internal Form1 form = new Form1();
internal void Start()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(form);
}
private delegate void StopDelegate();
public void Stop()
{
if (form.InvokeRequired)
{
form.Invoke(new StopDelegate(Stop));
return;
}
form.Close();
}
private delegate void DisplayDelegate(string s);
public void Display(string s)
{
if (form.InvokeRequired)
{
form.Invoke(new DisplayDelegate(form.Display), new[] {s});
}
}
}
而 Form1 只需要显示一些东西:
And Form1 just needs something to display:
public void Display(string s)
{
textBox1.Multiline = true;
textBox1.Text += s;
textBox1.Text += Environment.NewLine;
}
这篇关于在 Application.Run() 之后更新表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!