问题
I have a button on a form which opens a new form as an owned form. (It's very simple, no other logic than below)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
Form form = new Form();
form.Show(this);
}
}
My problem is as follows:
- If I click the button to get an instance of an owned form and drag it to it's own monitor.
- Maximize the owned form
- Minimize the original main form (Form1)
- Restore the original main form (Form1)
Then on restore the maximized owned form is no longer maximized but has a state of Normal.
Edit: The Owned form is styled as a tool window so I cannot break the Owner/Owned relationship. It appears to be a thing with winforms but I know it should be possible to correct since VS behaviors correctly and restores the window to Maximized rather than to Normal.
回答1:
Here's one possibility...
Add a property to the Owned form to track its last FormWindowState
(could just be private
if you don't care to expose it):
private FormWindowState _lastState;
public FormWindowState LastWindowState { get { return _lastState; } }
Add an override for WndProc
to the Owned form:
protected override void WndProc(ref Message message)
{
const Int32 WM_SYSCOMMAND = 0x0112;
const Int32 SC_MAXIMIZE = 0xF030;
const Int32 SC_MINIMIZE = 0xF020;
const Int32 SC_RESTORE = 0xF120;
switch (message.Msg)
{
case WM_SYSCOMMAND:
{
Int32 command = message.WParam.ToInt32() & 0xfff0;
switch (command)
{
case SC_MAXIMIZE:
_lastState = FormWindowState.Maximized;
break;
case SC_MINIMIZE:
_lastState = FormWindowState.Minimized;
break;
case SC_RESTORE:
_lastState = FormWindowState.Normal;
break;
}
}
break;
}
base.WndProc(ref message);
}
Finally, add a handler for the Owned form's VisibleChanged
event:
private void Form2_VisibleChanged(object sender, EventArgs e)
{
WindowState = _lastState;
}
来源:https://stackoverflow.com/questions/18234312/maximized-owned-form-not-restoring-correctly