Maximized owned Form not restoring correctly

不羁的心 提交于 2019-12-11 14:49:08

问题


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:

  1. If I click the button to get an instance of an owned form and drag it to it's own monitor.
  2. Maximize the owned form
  3. Minimize the original main form (Form1)
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!