5

Code for the form:

public partial class Foo: Form
{
    public Foo()
    {
        InitializeComponent();
    }

    protected override void OnLoad(EventArgs e)
    {
        // Form already visible here when Maximized from calling code
        base.OnLoad(e);
    }
}

Calling code:

Foo foo = new Foo();
foo.WindowState = FormWindowState.Maximized;
foo.ShowDialog();

When the code enters the OnLoad event, the Foo form is already displayed on the screen. If I remove the foo.WindowState = FormWindowState.Maximized statement, then the Foo form is not visible in the OnLoad event (as it should be).

Why is it and what can I do to fix the issue? The issue being that when the form is set to Maximized, it shows up too early in the cycle.

Note that there is a similar question, but it focused on UI antics and didn't really address the problem.

Community
  • 1
  • 1
AngryHacker
  • 59,598
  • 102
  • 325
  • 594
  • This question doesn't really make sense. What is "the issue"? Is it that you don't want the form maximized? – Chris Shain Jun 05 '12 at 22:35
  • @ChrisShain I don't want the form to show too early. – AngryHacker Jun 05 '12 at 22:37
  • ummm don't call ShowDialog until you're ready for it to be seen??? – Paul Farry Jun 05 '12 at 22:38
  • So if you don't want it to show too early, don't set `WindowState = FormWindowState.Maximized;` in the constructor. I assume there is a reason for doing that- what is that reason? – Chris Shain Jun 05 '12 at 22:45
  • @ChrisShain Yes. The reason is that the OnLoad event on the form is used to populate all kinds of lookups and setup bindings, which takes 2-3 seconds. In Maximized mode, the user seems a blank form covering the screen, which is ugly. In non-maximized mode (e.g. Normal), the form is not present until the code has moved out of the OnLoad event. I'd like the experiences of Maximized and Normal form states be identical. – AngryHacker Jun 05 '12 at 22:48
  • @PaulFarry The form's OnLoad event is used to populate the form, thus I must call ShowDialog, in order to engage the event. – AngryHacker Jun 05 '12 at 22:49

1 Answers1

5

This kind of problem usually warrants some careful thought about how you're doing things. A rethink on your strategy for loading, binding and displaying forms may be in order. However, for a simple solution, you could do this:

Foo foo = new Foo();
foo.Shown += (s, a) => foo.WindowState = FormWindowState.Maximized;            
foo.ShowDialog();

This way, you won't maximize the form until the Shown event is raised, which happens after OnLoad().

Igby Largeman
  • 16,495
  • 3
  • 60
  • 86
  • Wow, that worked. The question still remains why the form shows up too early. – AngryHacker Jun 05 '12 at 23:52
  • 2
    It's a bug, [reported 5 years ago](http://connect.microsoft.com/VisualStudio/feedback/details/288032). Sadly Microsoft doesn't really invest in improving the winforms platform anymore. – Igby Largeman Jun 06 '12 at 00:48