ispiro
ispiro

Reputation: 27633

How to run code when form is shown?

I thought the Load event might help, but the following code just shows “Done” immediately.

public Form1()
{
    InitializeComponent();
    Load += new EventHandler(Form1_Load);
}

void Form1_Load(object sender, EventArgs e)
{
    System.Threading.Thread.Sleep(3000);
    Text = "Done";
}

How do I make it Sleep after the form is shown?

Thanks.

Upvotes: 11

Views: 40895

Answers (4)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112259

Thread.Sleep(3000); in the Load event handler delays the form opening for 3 seconds. This why it does not work as you expect. A timer is the best solution.

Upvotes: 0

Tigran
Tigran

Reputation: 62248

I would suggest do not block a form, process something and after show in its title "Done", cause that what you want to do, I presume. This gives to the user blocked UI feeling, which is not good.

It's definitely better to show some temporary "Wait for..." form and on completion of the operation/calculation you perform, show your main form.

Much more UX focused design.

Upvotes: 3

Rodolfo Neuber
Rodolfo Neuber

Reputation: 3451

There is a Shown event for a windows form. Check out: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.shown.aspx

Or if you are lazy, here you go:

public Form1()
{
    InitializeComponent();
    Shown += Form1_Shown;
}

private void Form1_Shown(object sender, EventArgs e) 
{
    System.Threading.Thread.Sleep(3000);
    Text = "Done";
}

Enjoy.

Upvotes: 27

Pedro
Pedro

Reputation: 12328

You could start a Timer in the Form1_Load method and link its Elapsed event to a method that displays the message.

Upvotes: 1

Related Questions