【问题标题】:Windows Form color changingWindows 窗体颜色变化
【发布时间】:2010-04-15 15:16:55
【问题描述】:

所以我正在尝试制作一个 MasterMind 程序作为一种练习。

  • 40 个图片框的字段(4 行,10 行)
  • 6 个按钮(红、绿、橙、黄、蓝、紫)

当我按下其中一个按钮(假设是红色按钮)时,图片框会变为红色。
我的问题是如何遍历所有这些图片框?
我可以让它工作,但前提是我写:
这当然是没有办法写这个的,会带我无数行包含基本相同的内容。

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

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

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

最好的问候。

【问题讨论】:

    标签: c#


    【解决方案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
    }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        我不会使用图片框,而是使用单个图片框,使用 GDI 直接在其上绘图。结果更快了,它会让你编写更复杂的涉及精灵和动画的游戏;)

        学习方法很容易。

        【讨论】:

        • 真的不知道你在说什么,可能有多简单=)。
        猜你喜欢
        • 2011-12-28
        • 1970-01-01
        • 2017-03-24
        • 1970-01-01
        • 1970-01-01
        • 2010-09-10
        • 1970-01-01
        • 2014-10-06
        • 1970-01-01
        相关资源
        最近更新 更多