Home > OS >  How to change the ForeColor of a disabled button
How to change the ForeColor of a disabled button

Time:06-16

So I have this button that launches another program. I disable it after launch to prevent double launch situations. Problem is the ForeColor changes from white to black which doesnt look good against my dark BackColor. How do I make the ForeColor not change when disabling or even change it after disable?

CodePudding user response:

You need to use EnabledChanged and paint events of the current button. Suppose your button name is button1.

    private void button1_EnabledChanged(object sender, EventArgs e)
    {
        Button currentButton = (Button)sender;
        button1.ForeColor =  currentButton.Enabled== false ? Color.White : currentButton.ForeColor ;
        button1.BackColor = currentButton.Enabled == false? Color.Black : currentButton.BackColor;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        button1.Enabled = false;
    }

    private void button1_Paint(object sender, PaintEventArgs e)
    {
        Button btn = (Button)sender;
        var solidBrush = new SolidBrush(btn.ForeColor);
        var stringFormat = new StringFormat
        {
            Alignment = StringAlignment.Center,
            LineAlignment = StringAlignment.Center
        };
       
        e.Graphics.DrawString(button1.Text, btn.Font, solidBrush, e.ClipRectangle, stringFormat);
        solidBrush.Dispose();
        stringFormat.Dispose();
    }

CodePudding user response:

You can add some css to target that element when it is in disabled mode, for example:

.my-button:disabled {
    // Apply styling here
}
  • Related