设置背景色为禁用按钮Windows窗体
本文关键字:按钮 Windows 窗体 置背景色 | 更新日期: 2023-09-27 18:04:41
我有一个按钮在我的windows窗体,我需要启用/禁用。当禁用时,我需要改变它的背景色并保留前色,以显示它是禁用的。
以下是我所尝试的。这保留了前色(这里是白色),但不改变背景色
private void button1_EnabledChanged(object sender, System.EventArgs e)
{
buttonScan.ForeColor = Color.White;
buttonScan.BackColor = Color.Aqua;
}
private void button1_Paint(object sender, PaintEventArgs e)
{
var btn = (Button)sender;
var drawBrush = new SolidBrush(btn.ForeColor);
var sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center};
e.Graphics.DrawString(btn.Text, btn.Font, drawBrush, e.ClipRectangle, sf);
drawBrush.Dispose();
sf.Dispose();
}
当按钮被禁用时,我需要改变背景色
如果你想使用你的自定义颜色,你需要将UseVisualStyleBackColor设置为false,否则该颜色将只应用于鼠标经过的按钮。
一个简单的测试上传到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));
}
}