1

每当鼠标进入按钮时,我都想在按钮上绘图。我希望在按钮文本后面绘制矩形。我有以下代码可以绘制到它上面:

private void button1_MouseEnter(object sender, EventArgs e)
{
    Graphics g = this.button1.CreateGraphics();
    LinearGradientBrush myBrush = new
        LinearGradientBrush(
        this.button1.ClientRectangle,
        Color.Red, 
        Color.AliceBlue, 
        LinearGradientMode.Horizontal
    );
    g.FillRectangle(myBrush, this.button1.ClientRectangle);
}

我想知道如何做到这一点,如果可以不制作自定义按钮。

如果有人有任何建议/解决方案,请在此处发布。

谢谢!

4

1 回答 1

2

我认为最简单的方法是创建一个自定义按钮,并覆盖它的OnPaint方法来进行绘图。然后您可以在源文件中替换ButtonCustomBtn并使用新按钮。

class CustomBtn : Button
{
    private bool ShouldDraw = false;
    private LinearGradientBrush myBrush = null;

    protected override void OnMouseEnter(EventArgs e)
    {
        base.OnMouseEnter(e);
        ShouldDraw = true;
    }

    protected override void OnMouseLeave(EventArgs e)
    {
        base.OnMouseLeave(e);
        ShouldDraw = false;
    }

    protected override void OnPaint(PaintEventArgs pevent)
    {
        base.OnPaint(pevent);
        if (ShouldDraw)
        {
            if (myBrush == null || (myBrush != null && myBrush.Rectangle != ClientRectangle))
            {
                myBrush = new LinearGradientBrush( ClientRectangle, Color.Red, Color.AliceBlue, LinearGradientMode.Horizontal );
            }
            pevent.Graphics.FillRectangle(myBrush, ClientRectangle);
            TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak;
            TextRenderer.DrawText(pevent.Graphics, Text, Font, ClientRectangle, ForeColor, flags);
        }
    }
}
于 2012-05-06T07:42:39.887 回答