如何在 Button.OnPaint 中绘制悬停和鼠标按下颜色

问题描述

我应该如何在 OnPaint 中绘制按钮背景,包括悬停和鼠标按下的颜色?

下面的代码只绘制背景颜色。鼠标进入时不绘制鼠标悬停颜色,单击时不绘制鼠标下移颜色。

我应该调用 base.OnPaintBackground 的替代方法吗?

protected override void OnPaint(PaintEventArgs e)
{
    // Does not draw hover and mousedown colors
    base.OnPaintBackground(e);

    e.Graphics.DrawString(Text,Font,new SolidBrush(ForeColor),0);
}

解决方法

这是我最后的结果。我对 ButtonRenderer.DrawButton() 不满意,因为我认为 base.OnPaintBackground() 应该处理鼠标悬停和单击绘图。不过,这很好用。

protected override void OnPaint(PaintEventArgs e)
{
    // Background painting
    base.OnPaintBackground(e);
    bool MouseInControl = e.ClipRectangle.Contains(PointToClient(Cursor.Position));
    if (MouseInControl)
        ButtonRenderer.DrawButton(e.Graphics,e.ClipRectangle,System.Windows.Forms.VisualStyles.PushButtonState.Normal);

    // Now paint other stuff on top
}