Search code examples
c#winformspassword-protectionmaximize-window

Maximize button that triggers password prompt before maximizing?


Short Explanation: I'm trying to create a pop-up Password prompt that is fired when the Maximize-window button is clicked.

Longer Explanation: I'm working on a GUI whose default dimensions hide sensitive controls from the user. Clicking on the Maximize-window button will reveal those controls, but I want to prevent easy access to casual users. Ideally I'd like a simple Password prompt to pop up when the Maximize-window button is clicked, which requires a password BEFORE the Maximize-window action takes place.

I've tried using a MessageBox and a separate form, but I can't seem to prevent the Maximize-window action from taking place before the pop-up appears. Any help would be greatly appreciated.


Solution

  • There is no OnMaximize event on WindowsForms. Fortunately, you can manipulate the WndProc event to catch the System Message that corresponds to a click in the maximize button.

    Try putting this code on the code-behind of your form:

    EDIT: Update to also catch a double-click in the title bar (suggested by Reza Aghaei answer).

    protected override void WndProc(ref Message m)
    {
        // 0x112: A click on one of the window buttons.
        // 0xF030: The button is the maximize button.
        // 0x00A3: The user double-clicked the title bar.
        if ((m.Msg == 0x0112 && m.WParam == new IntPtr(0xF030)) || (m.Msg == 0x00A3 && this.WindowState != FormWindowState.Maximized))
        {
            // Change this code to manipulate your password check.
            // If the authentication fails, return: it will cancel the Maximize operation.
            if (MessageBox.Show("Maximize?", "Alert", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                // You can do stuff to tell the user about the failed authentication before returning
                return;
            }
        }
    
        // If any other operation is made, or the authentication succeeds, let it complete normally.
        base.WndProc(ref m);
    }