Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run code when form is shown?

Tags:

c#

winforms

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.

like image 930
ispiro Avatar asked Sep 18 '11 16:09

ispiro


People also ask

When to start executing code following the form load event?

To best answer the question about when to start executing code following the form load event is to monitor the WM_Paint message or hook directly in to the paint event itself. Why? The paint event only fires when all modules have fully loaded with respect to your form load event.

How to get form to execute when form is activated?

You could also try putting your code in the Activated event of the form, if you want it to occur, just when the form is activated. You would need to put in a boolean "has executed" check though if it is only supposed to run on the first activation.

When is the form shown event raised?

"The Shown event is only raised the first time a form is displayed; subsequently minimizing, maximizing, restoring, hiding, showing, or invalidating and repainting will not raise this event." Show activity on this post. (change "this" to your form variable if you are handling the event on an instance other than "this").

How to get formready to work with startupevent?

// Option: Set FormReady to your controls manulaly ie. CustomControl.FormReady = true; or subscribe to the StartUpEvent event inside your class and use that as your entry point for validating and unleashing its code. // // Many options: The rest is up to you! } #endregion }


2 Answers

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.

like image 149
Rodolfo Neuber Avatar answered Oct 05 '22 08:10

Rodolfo Neuber


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.

like image 26
Tigran Avatar answered Oct 05 '22 06:10

Tigran