Home > Enterprise >  c# .NET 6.0 : WindowState, how to tell if the form was maximized before it was minimized
c# .NET 6.0 : WindowState, how to tell if the form was maximized before it was minimized

Time:02-20

Although I'm using C# .NET 6.0 this will probably relate to other frameworks also.

Take a Windows Form App with a resizable form that can be minimized and maximized. The user minimizes the form after they have maximized it. When the user restores the window from the taskbar the form will return to maximized. However, if I need to unminimize the form programmatically I need to use the WindowState property, but if I use Normal it will change the form back to regular size if I use Maximized it'll change it to maximized if the form was previously normal. How do I easily determine if the minimized form was previously in a maximized state? I am currently doing this by using the Resize event and reading WindowState in that event to record the state of the window. But it's rather a messy solution, is there a less greasy way to do this?

    bool isMaximized = false;
    private void Form_Resize(object? sender, EventArgs e)
    {
        switch (WindowState)
        {
            case FormWindowState.Normal:
                isMaximized = false;
                break;
            case FormWindowState.Maximized:
                isMaximized = true;
                break;
        }
    }

    private void ShowForm()
    {
        if (WindowState == FormWindowState.Minimized)
        {
            WindowState = isMaximized ? FormWindowState.Maximized : FormWindowState.Normal;
        }
    }

CodePudding user response:

I think no, but did want to point out the code you have seems verbose compared to storing a FormWindowState:

private FormWindowState _prev;
private void Form_Resize(object? sender, EventArgs e)
{
    if(WindowState != FormWindowState.Minimized) _prev = WindowState;
}

private void Restore()
{
    WindowState = _prev;
}
  •  Tags:  
  • c#
  • Related