Event when a window gets maximized/un-maximized

Viewed 71259

Is there an event that is fired when you maximize a Form or un-maximize it?

Before you say Resize or SizeChanged: Those get only fired if the Size actually changes. If your window happens to be equal in size to the maximized window, they do not fire. Location looks like the next best bet, but that again feels like gambling on a coincidence.

10 Answers

A complete solution with maximize, minimize, restore and correct remove of the lower bits which are used for internal purposes only.

protected override void WndProc(ref Message m)
{
    const int WM_SYSCOMMAND = 0x0112;
    const int SC_MAXIMIZE = 0xF030;
    const int SC_MINIMIZE = 0xF020;
    const int SC_RESTORE = 0xF120;

    // Call beofre - don't use when "call after" is used
    // dependig on the needs may be called before, after or even never (see below)
    // base.WndProc(ref m);

    if (m.Msg == WM_SYSCOMMAND)
    {
        /// <see cref="https://docs.microsoft.com/en-us/windows/win32/menurc/wm-syscommand"/>
        /// Quote:
        /// In WM_SYSCOMMAND messages, the four low - order bits of the wParam parameter 
        /// are used internally by the system.To obtain the correct result when testing 
        /// the value of wParam, an application must combine the value 0xFFF0 with the 
        /// wParam value by using the bitwise AND operator.
        int wParam = (m.WParam.ToInt32() & 0xFFF0);

        Debug.WriteLine($"Received param: { Convert.ToString(wParam, 16) } ");

        if (wParam == SC_MAXIMIZE)
        {
            
        }

        if (wParam == SC_MINIMIZE)
        {
            
        }

        if (wParam == SC_RESTORE)
        {
            
        }
    }

    // Call after - don't use when "call before" is used
    base.WndProc(ref m);
}
Related