Color Change in Windows Form

So, I am trying to make the MasterMind program as an exercise.

  • Field of 40 picture boxes (line of 4, 10 lines)
  • 6 buttons (red, green, orange, yellow, blue, purple)

When I click one of these buttons (allows you to accept red), then the image window turns red.
My question is, how can I iterate over all these image fields?
I can make it work, but only if I write:
And that doesn’t mean that we cannot write it, I will have countless lines that contain basically the same.

        private void picRood_Click(object sender, EventArgs e)
    {
        UpdateDisplay();
        pb1.BackColor = System.Drawing.Color.Red;
    }

Press the red button → the first screenshot will turn red

Press the blue button → the second screen will turn blue
Press the orange button → the third picture will be orange
And so on ...

I had a previous similar program that simulates a traffic light, there I can assign a value for each color (red 0, orange 1, green 2).
Something similar is needed or exactly how I address all these boxes with pictures and make them appropriate to the button.

Regards.

+3
source share
3 answers

, PictureBox Paint. PictureBox, .

:

// define a class to help us manage our grid
public class GridItem {
    public Rectangle Bounds {get; set;}
    public Brush Fill {get; set;}
}

// somewhere in your initialization code ie: the form constructor
public MyForm() {
    // create your collection of grid items
    gridItems = new List<GridItem>(4 * 10); // width * height
    for (int y = 0; y < 10; y++) {
        for (int x = 0; x < 4; x++) {
            gridItems.Add(new GridItem() {
                Bounds = new Rectangle(x * boxWidth, y * boxHeight, boxWidth, boxHeight),
                Fill = Brushes.Red // or whatever color you want
            });
        }
    }
}

// make sure you've attached this to your pictureBox Paint event
private void PictureBoxPaint(object sender, PaintEventArgs e) {
    // paint all your grid items
    foreach (GridItem item in gridItems) {
        e.Graphics.FillRectangle(item.Fill, item.Bounds);
    }
}

// now if you want to change the color of a box
private void OnClickBlue(object sender, EventArgs e) {
    // if you need to set a certain box at row,column use:
    // index = column + row * 4
    gridItems[2].Fill = Brushes.Blue; 
    pictureBox.Invalidate(); // we need to repaint the picturebox
}
+1

pic, :

foreach (PictureBox pic in myPanel.Controls)
{
    // do something to set a color
    // buttons can set an enum representing a hex value for color maybe...???
}
0

I would not use graphic boxes, but instead would use a single graphic box drawn directly on it using GDI. The result is much faster, and it will make you write more complex games involving sprites and animations;)

It is very easy to find out.

0
source

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


All Articles