button按钮在disable状态下,字体为黑色,设置前景色无效。为解决该问题,自定义一个button,带图标。
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
public class MyButton : Button
{
private string m_Text = string.Empty;// 新文本
private Image m_Image = null;// 新图片
// 可用的前景色
private Color enableForeColor = Color.White;
public Color EnableForeColor
{
get { return enableForeColor; }
private set { enableForeColor = value; }
}
// 不可用的前景色
private Color disableForeColor = Color.FromArgb(96, 96, 96);
public Color DisableForeColor
{
get { return disableForeColor; }
private set { disableForeColor = value; }
}
// 可用的前景图片
private Image enableImage = null;
public Image EnableImage
{
set { enableImage = value; }
}
// 不可用的前景图片
private Image disableImage = null;
public Image DisableImage
{
set { disableImage = value; }
}
/// <summary>
/// 重写text
/// </summary>
public new string Text
{
get
{
return m_Text;
}
set
{
if (base.Text != string.Empty)
{
base.Text = string.Empty;
}
if (!string.IsNullOrEmpty(value) && m_Text != value)
{
m_Text = value;
this.Invalidate();
}
}
}
/// <summary>
/// 重写image
/// </summary>
public new Image Image
{
get
{
return m_Image;
}
set
{
if (base.Image != null)
{
base.Image = null;
}
if (value != null && m_Image != value)
{
m_Image = value;
}
}
}
public MyButton()
{
this.Paint += MyButton_Paint;
this.EnabledChanged += MyButton_EnabledChanged;
this.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.FlatAppearance.BorderSize = 0;
}
/// <summary>
/// 可用状态变化
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void MyButton_EnabledChanged(object sender, EventArgs e)
{
this.ForeColor = this.Enabled ? enableForeColor : disableForeColor;
this.Image = this.Enabled ? enableImage : disableImage;
}
/// <summary>
/// 重绘
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MyButton_Paint(object sender, PaintEventArgs e)
{
// 绘制文本
if (!string.IsNullOrEmpty(m_Text))
{
TextRenderer.DrawText(e.Graphics, m_Text, this.Font, e.ClipRectangle, this.ForeColor);
}
// 绘制边框
Pen p = new Pen(this.ForeColor, 0.5F);
e.Graphics.DrawRectangle(p, e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.Width - 1, e.ClipRectangle.Height - 1);
// 绘制图片
if (m_Image != null)
{
Size size = TextRenderer.MeasureText(e.Graphics, m_Text, this.Font);
float x = (float)(this.Width - size.Width) / 2;
float y = (float)(this.Height - m_Image.Height) / 2;
if (this.TextImageRelation == TextImageRelation.TextBeforeImage)// 图片在右边
{
e.Graphics.DrawImage(m_Image, x + size.Width, y, m_Image.Width, m_Image.Height);
}
else// 图片在左边
{
e.Graphics.DrawImage(m_Image, x - m_Image.Width, y, m_Image.Width, m_Image.Height);
}
}
}
}