C # - Automatically add the number of "X" buttons, one by one.

I have a windows form where I add a control button for each monitor connected to the computer. Naturally, with a large number of displays from PC to PC, I want to automatically add a button to the display and add them so that they appear in a row.

Currently, my code looks like this:

 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);

                }

This works, however, it simply puts each button on top of each other where there is more than one display (as I expected):

Currently.

What I want to achieve is that each button is added, but next to each other. I tried various streams, google searches, etc. To no avail. Can someone point me in the right direction?

What I'm trying to achieve.

+4
3

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);
}

.

: counter/indexer .

+7

, - ?

Location = new Point(12, 70),

,

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

100 - - screen_index

+3

. :

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

:

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

-. , screenNumber - , , .

+3
source

Source: https://habr.com/ru/post/1655936/


All Articles