0
votes

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
I have tried to listen to the message queue for events of it getting restored but I only get these for the main form, not the owned form. When I check the state of the owned form at that point it is correctly Maximised.Adam S-Price
If they aren't to behave as Owner and Owned, then why do it? Leave it "un-owned" and it does what you want.DonBoitnott
The Owned form is styled as a tool window which should only be visible if the main form is visible.Adam S-Price
Is it only to ensure that Owner always closes Owned? If so, just make that happen manually, and leave it un-Owned.DonBoitnott
That would require changing a lot of code to make sure the forms are closed and minimized and sit correctly ontop of the main form. I don't see that as a solution tbh.Adam S-Price

1 Answers

1
votes

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;
}