将backcolor设置为禁用按钮窗体

时间:2014-05-23 09:39:28

标签: c# winforms button background-color

我的Windows窗体中有一个按钮,我需要启用/禁用。禁用时我需要更改其背景颜色并保留前景色以显示它已被禁用。

以下是我的尝试。这保留了forecolor(白色),但不会改变背景颜色

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();
    }

我需要在禁用按钮时更改背景颜色

1 个答案:

答案 0 :(得分:0)

如果您想使用自定义颜色,则需要将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));
}
}