C#:更改按钮BackColor无效

我在Windows窗体中遇到C#按钮问题。

我以编程方式创建了许多按钮,然后将它们添加到表单中。

有趣的是,除了修改BackColor之外,对这些按钮(位置和大小)的每次修改都很容易执行。 只有按钮的颜色保持不变。

代码看起来像这样:

 public class SimpleSortAlgDisplayer : ISortAlgDisplayer { #region ISortAlgDisplayer Member void ISortAlgDisplayer.Init(int[] Data) { this.DataLength = Data.Length; this.DispWin = new CurrentSortStateWin(); this.DispWin.Show(); this.DispWin.Size = new Size(60 + (10 * this.DataLength), 120); this.myArrayElements = new Button[this.DataLength]; for (int i = 0; i < this.DataLength; i++) { this.myArrayElements[i] = new Button(); //begin of series of invoked actions this.myArrayElements[i].Size=new Size(5,(int)(((80)*(double)Data[i])/1000)); this.myArrayElements[i].Location = new Point(30 + (i * 10), 90-(this.myArrayElements[i].Size.Height)); this.myArrayElements[i].Enabled = true; this.myArrayElements[i].BackColor = Color.MidnightBlue; this.myArrayElements[i].UseVisualStyleBackColor = true; this.DispWin.Controls.Add(this.myArrayElements[i]); this.myArrayElements[i].Refresh(); } } 

想法有人吗?

这里也提出了类似的问题,但答案并不是很有帮助:

  • 尝试使用Invoke为我提供了尚未创建DispWin的运行时错误。
  • UseVisualStyleBackColor设置为false不会更改任何内容。
  • 仅在添加和格式化按钮后设置BackColorForeColor或显示DispWin也没有任何效果。

我哪里错了?

您正在尝试设置颜色,但之后您将覆盖它,说UseVisualStyleBackColor = true

如果要使用自定义颜色,则需要将UseVisualStyleBackColor设置为false否则颜色将仅在鼠标hover时应用于按钮。

一个简单的测试上传到GitHub

 public partial class mainForm : Form { Random randonGen = new Random(); public mainForm() { InitializeComponent(); } private void mainForm_Load(object sender, EventArgs e) { populate(); } private void populate() { Control[] buttonsLeft = createButtons().ToArray(); Control[] buttonsRight = createButtons().ToArray(); pRight.Controls.AddRange(buttonsRight); pLeft.Controls.AddRange(buttonsLeft); } private List 

结果

在此处输入图像描述

如果FlatStyle for按钮设置为System ,它将不显示任何背景颜色,而是使用系统颜色模板的背景颜色。

确保没有设置BackgroundImage。 这会覆盖BackColor。