按钮被禁用时如何避免颜色变化?

use*_*179 10 c# colors button backcolor winforms

我们有一个Windows Forms项目,有很多FlatStyle按钮.

当我们禁用按钮时,按钮的颜色会自动更改Frown | :(

有可能以某种方式覆盖它,所以我们可以自己控制颜色吗?

Har*_*rsh 16

您需要使用EnabledChanged事件来设置所需的颜色.这是一个例子.

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

根据您的要求使用所需的颜色.

您还需要使用paint事件.

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

}
Run Code Online (Sandbox Code Playgroud)


小智 5

要获得不太模糊的文本,请改用 TextRenderer 类:

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 the 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);
}
Run Code Online (Sandbox Code Playgroud)

并使用 Button1_EnabledChanged 方法,如 Harsh 的答案中所示。

  • 我会避免在绘画事件中设置属性。 (5认同)