繁体   English   中英

Windows窗体颜色变化

[英]Windows Form color changing

所以我试图将MasterMind程序作为一种练习。

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

当我按下其中一个按钮(假设红色按钮)时,图片框变为红色。
我的问题是我如何迭代所有这些图片框?
我可以让它工作,但只有我写:
而且这种情况无法写出来,这将带给我无数基本相同的线条。

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

按红色按钮 - >第一个图片框变为红色
按蓝色按钮 - >第二个图片框变为蓝色
按橙色按钮 - >第三个图片框变为橙色
等等...

我有一个以前类似的程序,模拟交通信号灯,我可以为每种颜色(红色0,橙色1,绿色2)分配一个值。
是否需要类似的东西,或者我如何确切地对齐所有这些图片框并使它们与正确的按钮相对应。

最好的祝福。

我不会使用控件,而是可以使用单个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
}

我会使用面板作为所有图片框的容器控件,然后:

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

我不会使用picturebox,而是使用单个图片框,使用GDI直接绘制到它上面。 结果要快得多,它会让你编写更复杂的游戏,包括精灵和动画;)

这很容易学习。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM