Search code examples
c#restoreminimizemaximizewindowstate

Using C# FormWindowState to restore up?


I'd like to detect if my application is minimized under certain situations, and if it is, the window needs to be restored. I can do that easily as follows:

if(this.WindowState == FormWindowState.Minimized) {
    this.WindowState = FormWindowState.Normal;
}

However, what happens if the user first maximizes the form, then minimizes it? I don't know whether to set the WindowState to FormWindowState.Normal or FormWindowState.Maximized. Is there a method or API call I can check to solve this problem?


Solution

  • The code shown below does what you need. Overriding the user's choice is pretty unwise btw.

    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
            mLastState = this.WindowState;
        }
        FormWindowState mLastState;
        protected override void OnResize(EventArgs e) {
            base.OnResize(e);
            if (mLastState != this.WindowState) {
                if (this.WindowState == FormWindowState.Minimized) this.WindowState = mLastState;
                else mLastState = this.WindowState;
            }
        }
    }