Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait until form is finished loading

Tags:

c#

winforms

Is there some sort of boolean that I can use to check whether the instance of a form is loaded, or otherwise wait until the form is loaded?

for example:

While(form_loaded == false) {
  Try {
    //do something
  }
  catch {
  }//do try catch so code won't barf
}

I keep getting the following exception:

A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll

Additional information: Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

This is what I am worrying about.

Additionally if a more detailed explanation is needed I can try to post some code and/or some more output debugging information.

like image 923
Bennett Yeo Avatar asked Sep 07 '13 17:09

Bennett Yeo


People also ask

Which function is called for loading of a window form?

Load Event (System. Windows. Forms) | Microsoft Learn.

What is form load event?

The Form Load Event in VB . NET. An important event you'll want to write code for is the Form Load event. You might want to, for example, set the Enabled property of a control to False when a form loads. Or maybe blank out an item on your menu.

Which event will occur whenever the User control load?

The Load event occurs when the handle for the UserControl is created. In some circumstances, this can cause the Load event to occur more than one time. For example, the Load event occurs when the UserControl is loaded, and again if the handle is recreated.


2 Answers

try to use the shown event something like this

 public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.Shown += new System.EventHandler(this.Form1_Shown);
    }

    private void Form1_Shown(object sender, EventArgs e)
    {

    }
}

hope this help

like image 185
BRAHIM Kamel Avatar answered Sep 19 '22 13:09

BRAHIM Kamel


The first event that is triggered after form is fully loaded is the Shown event. use it...


According to MSDN the event sequence is :

When application starts:

  • Control.HandleCreated
  • Control.BindingContextChanged
  • Form.Load
  • Control.VisibleChanged
  • Form.Activated
  • Form.Shown

When an application closes:

  • Form.Closing
  • Form.FormClosing
  • Form.Closed
  • Form.FormClosed
  • Form.Deactivate

And as @Henk Holterman stated in his answer, don't use busy waiting in an event driven form...

like image 26
Avi Turner Avatar answered Sep 19 '22 13:09

Avi Turner