c# - 一键更改按钮颜色
问题描述
我开始用 c# 编写代码,但我遇到了问题。基本上,我想顺时针跳颜色。例如,如果我单击橙色按钮,金色按钮变为白色,第二个按钮变为金色。我想对所有按钮都这样做,直到按钮下面的金色按钮变成金色,而其他按钮保持白色(顺时针)
我现在唯一的代码是:
if (button9.Enabled)
{
button2.BackColor = Color.Gold;
button1.BackColor = Color.White;
}
按钮 9 是跳跃按钮。
如果你能帮助我,我将不胜感激。
解决方案
这是一个简单的 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;
}
}
}
}
}
推荐阅读
- ios - Swift 属性仅在存在 didSet 时正确设置(可以为空)
- sql - 如何使用queryBuilder修复“错误:预期文字,得到'SELECT'”?
- c# - 进程说无效操作异常
- weblogic - Traefik 代理背后的 Weblogic 控制台访问
- hash - 使用 -d dgst 时 tpm2_verifysignature 失败
- c++ - 试图创建一个线程来向套接字发送消息。遇到与线程构造函数有关的 2 个错误
- java - 将嵌套 JSON 映射到 Java POJO
- python - 正在创建 model.manager,我相信我删除了数据库
- excel - 保存作为网页上超链接目标的文件
- python - 为什么我在 python 的 spearman 相关中得到 nan