TX_ TX_ - 2 months ago 11
C# Question

New area not repaints when user-drawn control size is increased

I think I'm missing something trivial here. I derived simple control directly from

Control
. I'm overriding
OnPaint
and painting the rectangle (
e.Graphics.DrawRectangle
)and a text inside it (
e.Graphics.DrawString
). I did not override any other members.

It paints itself well when the control is resized to the smaller size, but when it gets resized to the larger size, new area is not repainted properly. As soon as I resize it to the smaller size again, even if by one pixel, everything repaints correctly.

OnPaint
gets called properly (with appropriate
PaintEventArgs.ClipRectangle
set correctly to new area), but the new area is not painted (artifacts appear) anyway.

What am I missing?

EDIT:

Code:

protected override void OnPaint(PaintEventArgs e)
{
// Adjust control's height based on current width, to fit current text:

base.Height = _GetFittingHeight(e.Graphics, base.Width);

// Draw frame (if available):

if (FrameThickness != 0)
{
e.Graphics.DrawRectangle(new Pen(FrameColor, FrameThickness),
FrameThickness / 2, FrameThickness / 2, base.Width - FrameThickness, base.Height - FrameThickness);
}

// Draw string:

e.Graphics.DrawString(base.Text, base.Font, new SolidBrush(base.ForeColor), new RectangleF(0, 0, base.Width, base.Height));
}

private int _GetFittingHeight(Graphics graphics, int width)
{
return (int)Math.Ceiling(graphics.MeasureString(base.Text, base.Font, width).Height);
}


WTF?

Answer

Try adding this in your constructor:

public MyControl() {
  this.ResizeRedraw = true;
  this.DoubleBuffered = true;
}

and in your paint event, clear the previous drawing:

protected override void OnPaint(PaintEventArgs e) {
  e.Graphics.Clear(SystemColors.Control);
  // yada-yada-yada
}
Comments