Event when a window gets maximized/un-maximized

Suprising that no one mentioned the inbuilt .NET method.

This way you don't need to override the Window Message Processing handler.

It even captures maximize/restore events caused by double-clicking the window titlebar, which the WndProc method does not.

Copy this in and link it to the "Resize" event handler on the form.

    FormWindowState LastWindowState = FormWindowState.Minimized;
    private void Form1_Resize(object sender, EventArgs e) {

        // When window state changes
        if (WindowState != LastWindowState) {
            LastWindowState = WindowState;


            if (WindowState == FormWindowState.Maximized) {

                // Maximized!
            }
            if (WindowState == FormWindowState.Normal) {

                // Restored!
            }
        }

    }

Another little addition in order to check for the restore to the original dimension and position after the maximization:

protected override void WndProc(ref Message m)
{
    base.WndProc(ref m);

    // WM_SYSCOMMAND
    if (m.Msg == 0x0112)
    {
        if (m.WParam == new IntPtr(0xF030) // Maximize event - SC_MAXIMIZE from Winuser.h
            || m.WParam == new IntPtr(0xF120)) // Restore event - SC_RESTORE from Winuser.h
        {
            UpdateYourUI();
        }
    }
}

Hope this help.


You can do this by overriding WndProc:

protected override void WndProc( ref Message m )
{
    if( m.Msg == 0x0112 ) // WM_SYSCOMMAND
    {
        // Check your window state here
        if (m.WParam == new IntPtr( 0xF030 ) ) // Maximize event - SC_MAXIMIZE from Winuser.h
        {
              // THe window is being maximized
        }
    }
    base.WndProc(ref m);
}

This should handle the event on any window. SC_RESTORE is 0xF120, and SC_MINIMIZE is 0XF020, if you need those constants, too.

Tags:

C#

Winforms