I'm trying to update a the text inside a label in a Windows Forms launched from a Console Application, as an example I've created this code.
static void Main(string[] args)
{
Form form = new Form();
Label label = new Label();
label.Text = "hi";
form.Controls.Add(label);
form.ShowDialog();
Thread.Sleep(2000);
label.Text = "bye";
label.Invalidate();
label.Update();
//Refresh Doesn't work either
//_BuyLabel.Refresh();
Application.DoEvents();
}
I've done my research but my knowledge of Windows Forms is quite limited, the libraries for this are already included and are not a problem.
What else do I need to do to update the text or any other Control feature?
Try this:
class Program
{
private static Form form = new Form();
private static Label label = new Label();
static void Main(string[] args)
{
label.Text = "hi";
form.Controls.Add(label);
form.Load += Form_Load; // Add handle to load event of form
form.ShowDialog();
Application.DoEvents();
}
private async static void Form_Load(object sender, EventArgs e)
{
await Task.Run(() => // Run async Task for change label.Text
{
Thread.Sleep(2000);
if (label.InvokeRequired)
{
label.Invoke(new Action(() =>
{
label.Text = "bye";
label.Invalidate();
label.Update();
}));
}
});
}
}
I run this on my pc, and work.