gpt4 book ai didi

c# - 如何在 C# 中以编程方式将一堆控件居中

转载 作者:行者123 更新时间:2023-12-02 22:03:38 24 4
gpt4 key购买 nike

我是这个社区的新手,我有这个应用程序可以通过编程方式添加控件。我想将所有添加的控件居中,就像选择它们并在 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
}

提前致谢

VB理论

最佳答案

以下是如何将控件作为GROUP 居中。除了我们计算组的质心必须移动多远才能成为父控件的中心外,它几乎与以前相同。然后我们遍历所有控件并将它们的位置偏移那么多。这使它们都居中,同时保持它们彼此的相对位置:

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

}

关于c# - 如何在 C# 中以编程方式将一堆控件居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16482072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com