8

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.

3
  • 1
    Your code will not compile against any C# compiler (I know it's example/pseudo-code, but that's beside the point.) Commented Sep 7, 2013 at 17:06
  • Just use Form_Shown
    – user2509901
    Commented Sep 7, 2013 at 17:09
  • 1
    You need to do this the other way around. Don't start the thread until the form's Load event fires. Commented Sep 7, 2013 at 18:54

3 Answers 3

26

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

1
  • 3
    In general, the event should be subscribed to/delegated in the designer. Commented Sep 7, 2013 at 17:12
10

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...

6

You have a Loaded and a Shown event to pick from.

Windows is event driven so never wait for something in a loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.