首页 > 解决方案 > 一键更改按钮颜色

问题描述

我开始用 c# 编写代码,但我遇到了问题。基本上,我想顺时针跳颜色。例如,如果我单击橙色按钮,金色按钮变为白色,第二个按钮变为金色。我想对所有按钮都这样做,直到按钮下面的金色按钮变成金色,而其他按钮保持白色(顺时针)

你可以在这张图片中看到我上面解释的内容

我现在唯一的代码是:

if (button9.Enabled)
{
    button2.BackColor = Color.Gold;
    button1.BackColor = Color.White;
}

按钮 9 是跳跃按钮。

如果你能帮助我,我将不胜感激。

标签: c#winformswinforms-to-web

解决方案


这是一个简单的 WinForm 示例

可以按照代码注释中的序号(1.1~4.2)来获取代码思路:)

using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // 2.1 initialize a list, and add all buttons into it.
            this.Buttons.Add(button2);
            this.Buttons.Add(button3);
            this.Buttons.Add(button4);

            // 2.2. initialize high light index.
            HighlightIndex = 0;

            // 2.3. refresh all buttons' color.
            RefreshColor();
        }

        // 1.1 we use this List to store all buttons.
        private List<Button> Buttons = new List<Button>();

        // 1.2 indicated the index of the highlighted button
        private int HighlightIndex = 0;

        private void button1_Click(object sender, System.EventArgs e)
        {
            // 4.1 when user click the jump button, increme the highlight index.
            HighlightIndex = HighlightIndex + 1;
            if (HighlightIndex >= Buttons.Count)
            {
                HighlightIndex = 0;
            }

            // 4.2 refresh all buttons' color.
            RefreshColor();
        }

        private void RefreshColor()
        {
            // 3.1 loop all buttons by index.
            for (int i = 0; i < Buttons.Count; i++)
            {
                if (i == HighlightIndex)
                {
                    // 3.2 if the index equals the highlight button index, update BackColor as Gold.
                    Buttons[i].BackColor = Color.Gold;
                }
                else
                {
                    // 3.3 set normal button BackColor as White.
                    Buttons[i].BackColor = Color.White;
                }
            }
        }
    }
}

推荐阅读