gpt4 book ai didi

C#:更改按钮背景颜色无效

转载 作者:太空狗 更新时间:2023-10-30 00:12:10 24 4
gpt4 key购买 nike

我在使用 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();

}
}

有人有想法吗?

有人问了类似的问题here但它的答案不是很有帮助:

  • 尝试使用 Invoke 时出现运行时错误,即 DispWin 尚未创建。
  • UseVisualStyleBackColor 设置为 false 不会有任何改变。
  • 仅在添加和格式化按钮后设置 BackColorForeColor 或显示 DispWin 也没有效果。

我哪里错了?

最佳答案

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

如果您想使用自定义颜色,您需要将 UseVisualStyleBackColor 设置为 false,否则颜色只会在鼠标悬停时应用到按钮上。

一个简单的测试uploaded to 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<Button> createButtons()
{
List<Button> buttons = new List<Button>();

for (int i = 1; i <= 5; i++)
{

buttons.Add(
new Button()
{
Size = new Size(200, 35),
Enabled = true,
BackColor = GetColor(),
ForeColor = GetColor(),
UseVisualStyleBackColor = false,
Left = 20,
Top = (i * 40),
Text = String.Concat("Button ", i)
});
}

return buttons;
}

private Color GetColor()
{
return Color.FromArgb(randonGen.Next(255), randonGen.Next(255), randonGen.Next(255));
}
}

结果

enter image description here

关于C#:更改按钮背景颜色无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7127946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com