C# - 一个接一个地自动添加'X'个按钮.

Raw*_*wns 4 c# winforms

我有一个Windows窗体,我为连接到计算机的每个监视器添加一个按钮控件.当然,作为从PC到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);

                }
Run Code Online (Sandbox Code Playgroud)

这是有效的,它只是将每个按钮放在彼此的顶部,有多个显示器(正如我预期的那样):

目前.

我想要实现的是每个按钮都被添加,但是彼此相邻.我尝试了各种各样的线程,在谷歌等搜索无济于事.有人能指出我正确的方向吗?

我想要实现的目标.

410*_*one 7

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);
}
Run Code Online (Sandbox Code Playgroud)

应该这样做.

这个优点超过了其他答案:计数器/索引器内置于循环中.