显示窗体窗体时,控制台应用程序不接受输入
我创建了一个控制台应用程序。我想让标签(在表单上)显示我在控制台中输入的任何内容,但是当我运行表单时控制台挂起。
I have created a console application. I want to make the label (on the form) display whatever I type in the console, but the console hangs when I run the form.
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class Program
{
Label a;
static void Main(string[] args)
{
Form abc = new Form();
Label a = new Label();
a.Text = "nothing";
abc.Controls.Add(a);
Application.Run(abc);
System.Threading.Thread t=new System.Threading.Thread(Program.lol);
t.Start();
}
public static void lol()
{
Program p = new Program();
string s = Console.ReadLine();
p.a.Text = s;
lol();
}
}
}
Application.Run
将阻塞,直到窗体关闭。所以你应该在一个单独的线程上调用 。
Application.Run
will block until the form has closed. So you should call that on a separate thread.
然而,你的UI将在那个单独的线程上执行 - 触摸UI线程之外的UI元素,因此在调用 Console.ReadLine()
后,您需要使用 Control
However, your UI will then be executing on that separate thread - and you mustn't "touch" a UI element from a thread other than the UI thread, so after calling Console.ReadLine()
, you'll need to use Control.Invoke
or Control.BeginInvoke
to make changes in the UI.
此外,您还可以使用 您目前正在宣布一个名为 a
的本地变量,但不要为 Program.a
。
Additionally, you're currently declaring a local variable called a
, but never assigning a value to Program.a
.
以下是一个完整的版本:
Here's a complete version which works:
using System;
using System.Threading;
using System.Windows.Forms;
class Program
{
private Program()
{
// Actual form is created in Start...
}
private void StartAndLoop()
{
Label label = new Label { Text = "Nothing" };
Form form = new Form { Controls = { label } };
new Thread(() => Application.Run(form)).Start();
// TODO: We have a race condition here, as if we
// read a line before the form has been fully realized,
// we could have problems...
while (true)
{
string line = Console.ReadLine();
Action updateText = () => label.Text = line;
label.Invoke(updateText);
}
}
static void Main(string[] args)
{
new Program().StartAndLoop();
}
}