简体   繁体   中英

How to get the size of a docked control while the form is minimized?

I noticed that when a control is docked (or anchored), and the form is minimized, the Control.Size property returns an empty size (ie, {Width=0, Height=0} ). Here's some code to reproduce:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        GroupBox groupBox1 = new GroupBox();
        groupBox1.Dock = DockStyle.Fill;
        groupBox1.Text = "Some Title";
        this.Controls.Add(groupBox1);

        Task.Run(async () =>
        {
            while (true)
            {
                Console.Write(DateTime.Now.ToString("HH:mm:ss - "));
                Console.WriteLine(groupBox1.Size.ToString());
                await Task.Delay(1000);
            }
        });

    }
}

This will print the size of the GroupBox as long as the form is not minimized. Once the form is minimized, it starts printing zeros.

Is there a way to get the actual size of a docked/anchored control even if the form is minimized?

I'm looking for something similar to Form.RestoreBounds but for child controls, not the form itself. The controls will be docked in another child container.

A simple approach would be something like:

private class GroupBox2 : GroupBox {

    Size restoreSize = Size.Empty;

    protected override void OnSizeChanged(EventArgs e) {
        base.OnSizeChanged(e);
        // could also confirm the parent form is non-null and its WindowState is minimized
        Size s = this.Size;
        if (s.Width > 0 && s.Height > 0)
            restoreSize = s;
    }

    public Size RestoreSize {
        get {
            return restoreSize;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM