How to avoid color changes when button is disabled

2019-02-21 13:52发布

We have a Windows Forms project with quite a few FlatStyle buttons.

When we disable the buttons, the colors of the buttons are changed automatically Frown | :(

Is it possible to override this somehow, so we can control the colors ourselves?

4条回答
够拽才男人
2楼-- · 2019-02-21 14:28

I use ClientRectangle instead of e.ClipRectangle to avoid clip effect when the button is partialy repaint :

e.Graphics.Clear(BackColor);
using (var drawBrush = new SolidBrush(ForeColor))
using (var sf = new StringFormat
{
    Alignment = StringAlignment.Center,
    LineAlignment = StringAlignment.Center
})
{
    e.Graphics.DrawString(Text, Font, drawBrush, ClientRectangle, sf);
}
查看更多
相关推荐>>
3楼-- · 2019-02-21 14:31

I followed the following approach :- The Click() event of the button can be controlled using custom variable.

private bool btnDisabled;
private void btnClick(object sender, EventArgs e){
   if(!btnDisabled) return;}

This way the button doesn't even need to be disabled. The button still has the click feel but no action will be taken. Have to use the right colors to communicate that the button is disabled.

查看更多
神经病院院长
4楼-- · 2019-02-21 14:32

To get less-fuzzy text, use the TextRenderer class instead:

private void Button1_Paint(object sender, PaintEventArgs e)
        {
            Button btn = (Button)sender;
            // make sure Text is not also written on button
            btn.Text = string.Empty;
            // set flags to center text on button
            TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak;   // center the text
            // render the text onto the button
            TextRenderer.DrawText(e.Graphics, "Hello", btn.Font, e.ClipRectangle, btn.ForeColor, flags);
        }

And the Button1_EnabledChanged method as in Harsh's answer.

查看更多
冷血范
5楼-- · 2019-02-21 14:40

You need to use the EnabledChanged event to set the desired color. Here is an example.

private void Button1_EnabledChanged(object sender, System.EventArgs e)
{
Button1.ForeColor = sender.enabled == false ? Color.Blue : Color.Red;
Button1.BackColor = Color.AliceBlue;
}

Use the desired colors according to your requirement.

Also you need to use the paint event.

private void Button1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
dynamic btn = (Button)sender;
dynamic drawBrush = new SolidBrush(btn.ForeColor);
dynamic sf = new StringFormat {
    Alignment = StringAlignment.Center,
    LineAlignment = StringAlignment.Center };
Button1.Text = string.Empty;
e.Graphics.DrawString("Button1", btn.Font, drawBrush, e.ClipRectangle, sf);
drawBrush.Dispose();
sf.Dispose();

}
查看更多
登录 后发表回答