views:

392

answers:

3

Hello,

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?

+1  A: 

I think you should be able to call this.Show() and it will restore to the previous (visible) state.

Michael Bray
Calling `this.Show()` does not cause the window to be restored. Would be nice, though
jnylen
+1  A: 

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;
        }
    }
}
Hans Passant
I think you misinterpreted my question (or I didn't provide enough information). I'm not overriding the user's choice. This is a single-instance application with file associations. When the user opens a file, I want the existing instance to come to the front. Your code still solves my problem, though.
jnylen
A: 

Here's an approach that utilizes the OnResize method of the form

curtisk