我有一个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);
}
这是有效的,它只是将每个按钮放在彼此的顶部,有多个显示器(正如我预期的那样):
我想要实现的是每个按钮都被添加,但是彼此相邻。我尝试了各种各样的线程,在谷歌等搜索无济于事。有人能指出我正确的方向吗?
答案 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
是一个计数器,你必须在每次迭代时声明,初始化和递增。