Check if currently minimized window was in maximized or normal state at the time of minimization
Asked Answered
B

3

8

How can I distinguish whether a currently minimized window was maximized before that, as opposed to normal state in C#/WinForms?

if (WindowState == FormWindowState.Minimized)
{
    Properties.Settings.Default.Location = RestoreBounds.Location;
    Properties.Settings.Default.Size = RestoreBounds.Size;
    Properties.Settings.Default.IsMaximized = ...; // How do I know if the window would be restored to maximized?
}

I want to make the position and state of my window persistent using the application settings and I'm following https://mcmap.net/q/335007/-net-windows-forms-remember-windows-size-and-location but if the window was minimized at the time of closing I don't want it to start minimized on the next application start (which is what the answer there currently does).

What I want is for the window to start maximized if it had been maximized at the time it was minimized, and to start in its normal state if it had been in normal state at the time it was minimized.

Backgammon answered 7/9, 2016 at 9:13 Comment(1)
You can check inside WndProc method if forms has been minimized, take a look at this.Peery
S
4

WinForms does not expose any WindowStateChanged event then you have to track it by yourself. Windows will send a WM_SYSCOMMAND when form state changes:

partial class MyForm : Form
{
    public MyForm()
    {
        InitializeComponent();

        _isMaximized = WindowState == FormWindowState.Maximized;
    }

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_SYSCOMMAND)
        {
            int wparam = m.WParam.ToInt32() & 0xfff0;

            if (wparam == SC_MAXIMIZE)
                _isMaximized = true;
            else if (wparam == SC_RESTORE)
                _isMaximized = false;
        }

        base.WndProc(ref m);
    }

    private const int WM_SYSCOMMAND = 0x0112;
    private const int SC_MAXIMIZE = 0xf030;
    private const int SC_RESTORE = 0xf120;
    private bool _isMaximized;
}
Senescent answered 7/9, 2016 at 9:33 Comment(2)
While this works, can you please state why you masked the WParam value? Thanks.Advance
@alex You're right answer is too brief. from MSDN: "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."Senescent
B
2

You can use GetWindowPlacement (a native Win32 API function) on a minimized window, and read back the Flags member from the WindowPlacement struct. If bit 0x02 is set, then the window was maximized before it became minimized.

Beall answered 7/3, 2019 at 2:46 Comment(0)
M
0
if (this.WindowState == FormWindowState.Minimized)....
Minardi answered 20/2, 2023 at 22:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.