Using C# FormWindowState to restore up?
I'd like to detect if my application is minimized under certain situations, and if it i开发者_StackOverflow社区s, 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?
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;
}
}
}
I use this solution to restore forms in MDI form. First you have to define:
[DllImport("user32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
private const int SW_RESTORE = 9;
and when it comes to restore:
ShowWindowAsync(this.MdiChildren[i].Handle, this.SW_RESTORE);
This will restore form to the previous state without using additional state holders. Also you may find this article interesting
I think you should be able to call this.Show()
and it will restore to the previous (visible) state.
Here's an approach that utilizes the OnResize method of the form
https://stackoverflow.com/a/6837421/578731:
Not sure this will work for everybody, but I ran into this today and someone on the team suggested "have you tried Normal"?
Turns out he was right. The following seems to nicely restore your window:
if (myWindow.WindowState == WindowState.Minimized) myWindow.WindowState = WindowState.Normal;
That works just fine, restoring the window to Maximized if needed. It seems critical to check for the minimized state first as calling WindowState.Normal a second time will "restore" your window to its non-maximized state.
Hope this helps.
I think this is the best option (Microsoft said):
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
精彩评论