views:

45

answers:

1

I have created a custom control which derives from Panel. I use it to display an Image using BackgroundImage property. I override the OnClick method and set isSelected to true then call Invalidate method and draw a rectangle in overrided OnPaint. Everything goes just fine until I set DoubleBuffered to true. The rectangle is drawn and then it is erased and I can't get why this is happening.

public CustomControl()
    : base()
{
    base.DoubleBuffered = true;

    base.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true);
}

protected override void OnPaint(PaintEventArgs pe)
{
    base.OnPaint(pe);

    PaintSelection();
}

private void PaintSelection()
{
    if (isSelected)
    {
        Graphics graphics = CreateGraphics();
        graphics.DrawRectangle(SelectionPen, DisplayRectangle.Left, DisplayRectangle.Top, DisplayRectangle.Width - 1, DisplayRectangle.Height - 1);
    }
}
+4  A: 

In your PaintSelection, you should not create a new Graphics object, because that object will draw to the front buffer, which is then promptly overdrawn by the contents of the back buffer.

Paint to the Graphics passed in the PaintEventArgs instead:

protected override void OnPaint(PaintEventArgs pe)
{
    base.OnPaint(pe);
    PaintSelection(pe.Graphics);
}

private void PaintSelection(Graphics graphics)
{
    if (isSelected)
    {
        graphics.DrawRectangle(SelectionPen, DisplayRectangle.Left, DisplayRectangle.Top, DisplayRectangle.Width - 1, DisplayRectangle.Height - 1);
    }
}
Thomas
I knew that was easy, thank you!
Lemon