[visual-studio]如何中心控件以编程方式在 c# 中的一群

标签: Visual-Studio
发布时间: 2014/3/1 3:52:09
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我对这一社区,是新还有这以编程方式添加的控件的应用程序。我想中心所有已添加的控件就像选择它们并按中心上 Visual Studio。并不,我不想要居中每一拨出。这里是我用来获取所有控件的代码:

    private void GetAllControl(Control c, List<Control> list)
    {
        //gets all controls and saves them to a list
        foreach (Control control in c.Controls)
        {
            list.Add(control);
        }
    }

    //And then call it like this

        List<Control> list = new List<Control>();
        GetAllControl(PNL_custom, list);
        foreach (Play_panel m in list)
        {
            //And here I want to insert that center code
        }

感谢在前进

VBTheory

解决方法 1:

这里是如何中心作为一控件。它作为以前是几乎相同的除了我们计算多远质量中心集团已采取行动,成为父控件的中心。然后我们遍历所有的控件,那么多所抵消它们的位置。这中心他们同时保持其彼此之间的相对位置:

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

    private void button1_Click(object sender, EventArgs e)
    {
        List<Control> list = new List<Control>();
        GetAllControl(PNL_custom, list);
        CenterControlsAsGroup(list, Direction.Both); // center group in the center of the parent
    }

    public enum Direction
    {
        Vertical,
        Horizontal,
        Both
    }

    private void CenterControlsAsGroup(List<Control> controls, Direction direction)
    {
        if (controls.Count > 1)
        {
            int xSum = 0;
            int ySum = 0;
            Point center;
            foreach (Control ctl in controls)
            {
                center = new Point(ctl.Location.X + ctl.Width / 2, ctl.Location.Y + ctl.Height / 2);
                xSum = xSum + center.X;
                ySum = ySum + center.Y;
            }
            Point average = new Point(xSum / controls.Count, ySum / controls.Count);

            center = new Point(controls[0].Parent.Width / 2, controls[0].Parent.Height / 2);
            int xOffset = center.X - average.X;
            int yOffset = center.Y - average.Y;

            foreach (Control ctl in controls)
            {
                switch (direction)
                {
                    case Direction.Vertical:
                        ctl.Location = new Point(ctl.Location.X + xOffset, ctl.Location.Y);
                        break;

                    case Direction.Horizontal:
                        ctl.Location = new Point(ctl.Location.X, ctl.Location.Y + yOffset);
                        break;

                    case Direction.Both:
                        ctl.Location = new Point(ctl.Location.X + xOffset, ctl.Location.Y + yOffset);
                        break;
                }
            }
        }
    }

    private void GetAllControl(Control c, List<Control> list)
    {
        //gets all controls and saves them to a list
        foreach (Control control in c.Controls)
        {
            list.Add(control);
        }
    }

}
官方微信
官方QQ群
31647020