我有一个 Windows 窗体,我在其中为连接到计算机的每个显示器添加一个按钮控件。自然地,由于 PC 之间的显示器数量非常多,我想为每个显示器自动添加一个按钮并添加它们,以便它们显示在一行中。
目前我的代码是这样的:
foreach (var screen in Screen.AllScreens)
{
Button monitor = new Button
{
Name = "Monitor" + screen,
AutoSize = true,
Size = new Size(100, 60),
Location = new Point(12, 70),
ImageAlign = ContentAlignment.MiddleCenter,
Image = Properties.Resources.display_enabled,
TextAlign = ContentAlignment.MiddleCenter,
Font = new Font("Segoe UI", 10, FontStyle.Bold),
ForeColor = Color.White,
BackColor = Color.Transparent,
Text = screen.Bounds.Width + "x" + screen.Bounds.Height
};
monitorPanel.Controls.Add(monitor);
}
然而,这是有效的,它只是将每个按钮放在彼此之上,那里有多个显示器(如我所料):
我想要实现的是每个按钮都被添加,但彼此相邻排成一排。我试过各种线程,在谷歌上搜索等都无济于事。谁能指出我正确的方向?
最佳答案
IIRC AllScreens
可以被索引,所以:
var padding = 5;
var buttonSize = new Size(100, 60);
for (int i = 0; i < Screen.AllScreens.Length; i++)
{
var screen = Screen.AllScreens[i];
Button monitor = new Button
{
Name = "Monitor" + screen,
AutoSize = true,
Size = buttonSize,
Location = new Point(12 + i * (buttonSize.Width + padding), 70),
ImageAlign = ContentAlignment.MiddleCenter,
Image = Properties.Resources.display_enabled,
TextAlign = ContentAlignment.MiddleCenter,
Font = new Font("Segoe UI", 10, FontStyle.Bold),
ForeColor = Color.White,
BackColor = Color.Transparent,
Text = screen.Bounds.Width + "x" + screen.Bounds.Height
};
monitorPanel.Controls.Add(monitor);
}
应该可以了。
相对于其他答案的优势:循环中内置了计数器/索引器。
关于C# - 自动添加 'X' 个按钮,一个接一个。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39719606/