Search code examples
c#operating-systemwindowmaximize-windowwindowstate

How to make a maximize and normal windowstate all in one button


I want a simple way to maximize and normal windowstate all in one button (click me for image)

Method (code) c# coding -

    int maxornot;

    private void MaxButton_Click(object sender, EventArgs e)
    {

        this.WindowState = FormWindowState.Maximized;
        maxornot = 1;

        if (WindowState == FormWindowState.Minimized);
        {
            maxornot = 0;
        }

        if (maxornot == 0);
        {

        }

    }

if this method is pointless and there is a way to simplify the code then leave a code below.

p.s i didn't put much thought into how to get this method to work cause im just having headaches :P


Solution

  • From what you already showed in your code-example you want a button to Switch from FormWindowState.Normal to FormWindowState.Maximized and the other way as well.

    Now instead of Setting the FormWindowState of your form to Maximized at the start of your click Even you should first check the current state of your Window:

    if(this.WindowState == FormWindowState.Maximized)
        ... do something
    

    FormWindowState has 3 different states: Normal, Minimized and Maximized. In your case you don't need Minimized. All you have to do now is Switch between normal and maximized in your method depending on what is current active:

    if(this.WindowState == FormWindowState.Maximized)
        this.WindowState = FormWindowState.Normal;
    else
        this.WindowState = FormWindowState.Maximized;
    

    This 4 rows of code are all you need in the click event method.

    This simple if-else may also be converted to a ternary:

    this.WindowState = this.WindowState == FormWindowState.Maximized ? FormWindowState.Normal : FormWindowState.Maximized;