How to draw hover and mousedown colors in Button.OnPaint

260 Views Asked by At

How should I draw a Button background in OnPaint, including the hover and mouse down colors?

The code below only draws the background color. It does not draw the mouseover color when the mouse enters, and it does not draw the mousedownback color when you click.

Is there an alternative to base.OnPaintBackground I should be calling instead?

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, 0);
}
1

There are 1 best solutions below

0
Ray White On

Here is what I ended up with. I'm not happy with ButtonRenderer.DrawButton() because I believed base.OnPaintBackground() should have handled mouse hover and click drawing. Nevertheless, this works nicely.

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
}