C# - 自动添加' X'按钮数量,一个接一个。

时间:2016-09-27 08:19:53

标签: 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);

                }

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

Currently.

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

What I'm trying to achieve.

3 个答案:

答案 0 :(得分: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);
}

应该这样做。

这优于其他答案:计数器/索引器内置于循环中。

答案 1 :(得分:3)

我无法尝试,但是您不应该为每个按钮设置不同的位置吗?

Location = new Point(12, 70),

到例如。

Location = new Point(12 + (100 + gap) * screen_index, 70),

其中100是屏幕的宽度 差距是两个屏幕之间的差距 和screen_index索引从左到右

答案 2 :(得分:3)

您可以控制设置位置。你实际上是自己设置的:

Size = new Size(100, 60),
Location = new Point(12, 70)

我建议您使用每个按钮的大小增加位置,以及额外的填充:

Location = new Point(screenNumber * (100 + 5), 70)

或者其他什么。当然screenNumber是一个计数器,你必须在每次迭代时声明,初始化和递增。