1

I have a visually complex app with a lot of user interface components and 3rd party controls. On startup, it goes into a momentary conniption fit as everything resizes and stuff loads in Form_Load (but mostly due to resizing).

So I thought the solution might be to hide the form in the beginning of the Form_Load event and then show it at the end. However, it turns out that the form is already visible when the code enters Form_Load event.

How can I ensure that the form shows up when it's all ready and resized.

AngryHacker
  • 59,598
  • 102
  • 325
  • 594

3 Answers3

4

The Load event is executed on the UI thread. You should never put logic processing in a UI thread, as blocking it makes the UI unresponsive.

You should fork a new thread (see the Thread class) and do your startup logic there. A loading screen might be in order if it takes more than about 3 seconds. You'll need to use Form.Invoke() and delegates to perform any logic that interacts with the UI thread (e.g. changing a TextBox's text).

You're also incorrect in your assumption that the Load event occurs when the form is displayed. The Load event occurs after component initialization and before the form is displayed, then the Shown event occurs when the form is displayed.

Polynomial
  • 27,674
  • 12
  • 80
  • 107
2

This is similar to this SO Question having an accepted answer: Single Form Hide on Startup

This MSDN link related to boosting windows forms performance might also help you a lot: http://msdn.microsoft.com/en-us/magazine/cc163630.aspx

Community
  • 1
  • 1
S2S2
  • 8,322
  • 5
  • 37
  • 65
2

Your assumption is not entirely true: Form_Load (or to be precise: Load event handlers) executes when the form is being shown for the first time. It is true that at this point your form is already visible, although not usable, as your thread is blocked by your FormLoad function.

You have couple of options:

  1. Use splash screen, that has no controls and no top bar, so as it has no input, it would not be visible that your thread is blocked.
  2. Prepare your sizes and positioning before showing the form. It is perfectly legal to set sizes and positions before you call the Show. For instance in constructor of your form.
  3. Change the logic so that long calculations are not in the UI thread. Threading is simple with ThreadPool and then Form.Invoke, calling the methods on your form.
zmilojko
  • 2,125
  • 17
  • 27