Setting WindowState to Maximized causes window to appear too early

丶灬走出姿态 提交于 2019-12-08 18:08:05

问题


I read that the Load event is supposed to be fired after the window handle has been created, but before the window actually become visible. For the most part, this seems to be true. However, I've found that when I create a form with the WindowState property set to FormWindowState.Maximized (either via the VS designer, or programatically in the constructor), the window becomes visible prior to the Load event firing. For example:

using System;
using System.Windows.Forms;

namespace MyApplication
{
    public partial class MyForm : Form
    {
        public MyForm()
        {
            InitializeComponent();
            WindowState = FormWindowState.Maximized;
        }

        protected override void OnLoad(EventArgs e)
        {
            MessageBox.Show("OnLoad - notice that the window is already visible"); 
            base.OnLoad(e);
        }
    }
}

This in turn causes the displayed form to flicker a lot while its controls (which are laid out during the Form.Load event) are resized while the window is visible. If I did not set the state to be maximized, then all the resizing is done before the window is shown (which is what I would have expected).

I could hold off on setting the WindowState until the end of the Load event, but that still causes a lot of flickering because the window becomes visible and then all of the controls resize.

Any thoughts?


回答1:


Try to delay the change of WindowState until the first Activated event firing. This works for me in VB.NET with VS2005 and framework 2.0.




回答2:


If you need to put some diagnostic message in the Load event use System.Diagnostics.Debug.WriteLine();
If you use MessageBox, you will destroy the normal flow order of events.

protected override void OnLoad(EventArgs e)         
{             
     System.Diagnostics.Debug.WriteLine("onLoad");              
     base.OnLoad(e);         
} 

This post explain more details




回答3:


You have to set WindowState BEFORE InitializeComponent():

    public Form() //Constructor
    {
        WindowState = FormWindowState.Maximized;

        InitializeComponent();
    }



回答4:


Things that change the appearance of the window (resizing for instance) cause the window to become visible.

You could call .Hide() or .Visible = False in your ctor and make it visible again at the end of .Load



来源:https://stackoverflow.com/questions/9806651/setting-windowstate-to-maximized-causes-window-to-appear-too-early

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!