How to detect when a windows form is being minimized?

C#Winforms

C# Problem Overview


I know that I can get the current state by WindowState, but I want to know if there's any event that will fire up when the user tries to minimize the form.

C# Solutions


Solution 1 - C#

You can use the Resize event and check the Forms.WindowState Property in the event.

private void Form1_Resize ( object sender , EventArgs e )
{
    if ( WindowState == FormWindowState.Minimized )
    {
        // Do some stuff
    }
}

Solution 2 - C#

To get in before the form has been minimised you'll have to hook into the WndProc procedure:

    private const int WM_SYSCOMMAND = 0x0112;
    private const int SC_MINIMIZE = 0xF020; 

    [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
    protected override void WndProc(ref Message m)
    {
        switch(m.Msg)
        {
            case WM_SYSCOMMAND:
                int command = m.WParam.ToInt32() & 0xfff0;
                if (command == SC_MINIMIZE)
                {
                    // Do your action
                }
                // If you don't want to do the default action then break
                break;
        }
        base.WndProc(ref m);
    }

To react after the form has been minimised hook into the Resize event as the other answers point out (included here for completeness):

private void Form1_Resize (object sender, EventArgs e)
{
    if (WindowState == FormWindowState.Minimized)
    {
        // Do your action
    }
}

Solution 3 - C#

I don't know of a specific event, but the Resize event fires when the form is minimized, you can check for FormWindowState.Minimized in that event

Solution 4 - C#

For people who search for WPF windows minimizing event :

It's a bit different. For the callback use WindowState :

private void Form1_Resize(object sender, EventArgs e)
{
    if (WindowState == FormWindowState.Minimized)
    {
        // Do some stuff
    }
}

The event to use is StateChanged (instead Resize):

public Main()
{
    InitializeComponent();
    this.StateChanged += Form1_Resize;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJorge BrancoView Question on Stackoverflow
Solution 1 - C#Steve DignanView Answer on Stackoverflow
Solution 2 - C#ChrisFView Answer on Stackoverflow
Solution 3 - C#Dan FView Answer on Stackoverflow
Solution 4 - C#RaphLeFlamboyantView Answer on Stackoverflow