TX_ TX_ - 1 year ago 94
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

. I'm overriding
and painting the rectangle (
)and a text inside it (
). 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.

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

What am I missing?



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);


Answer Source

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) {
  // yada-yada-yada
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download