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

标签 c# winforms

我有一个 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);

                }

然而,这是有效的,它只是将每个按钮放在彼此之上,那里有多个显示器(如我所料):

Currently.

我想要实现的是每个按钮都被添加,但彼此相邻排成一排。我试过各种线程,在谷歌上搜索等都无济于事。谁能指出我正确的方向?

What I'm trying to achieve.

最佳答案

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/

相关文章:

.net - DataGridView 对 DateTime 列中的空值进行排序

c# - 多个索引可供收藏 - 只有一个作品

c# - 什么是锯齿状数组?

c# - 从 Angular 4 SPA 请求 Web API 时范围声明为空

c# - 禁用 ComboBox 控件中的右箭头键

c# - Winform 自定义控件 - Designer 随机停止初始化/调用构造函数

c# - 使用加法混合绘制图像

c# - 通用列表上的 Linq OrderBy 返回不完全按字母顺序排列的列表

c# - 如何将一个类传递给另一个类以进行代码隐藏?

c# - 设置 TabControl 对齐属性。 C# 窗体