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.
code:
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.Runwill block until the form has closed. So you should call that on a separate thread.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 useControl.InvokeorControl.BeginInvoketo make changes in the UI.Additionally, you’re currently declaring a local variable called
a, but never assigning a value toProgram.a.Here’s a complete version which works: