Windows窗体颜色更改

3

我正在尝试编写一个类似于练习的MasterMind程序。

  • 40个图片框(4行10列)
  • 6个按钮(红色,绿色,橙色,黄色,蓝色,紫色)

当我按下其中一个按钮(假设是红色),那么一个图片框就会变成红色。
我的问题是如何遍历所有这些图片框?
我可以让它工作,但只有在我写下以下代码时才能实现:
这当然不是一种好的写法,因为需要写出无数基本相同的代码行。

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

按下红色按钮 -> 第一个图片框变成红色
按下蓝色按钮 -> 第二个图片框变成蓝色
按下橙色按钮 -> 第三个图片框变成橙色
以此类推...

我之前写过一个类似的程序模拟交通信号灯,那里我可以为每种颜色分配一个值 (红色 0,橙色 1,绿色 2)。
是否需要类似的操作或者如何让所有这些图片框对应到正确的按钮。

最好的问候。

3个回答

1

我不会使用控件,相反你可以使用一个单独的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's 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's 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
}

0
我会使用一个面板作为所有图片框的容器控件,然后:
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
我不会使用pictureboxes,而是会使用单个picturebox,直接使用GDI进行绘制。结果更快,并且可以让你编写涉及精灵和动画的更复杂的游戏;)
学习起来非常容易。

真的不知道你在说什么,无论它有多简单 =)。 - Sef

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接