3
votes

I need to write some text to a paintbox, and I do it in the OnPaint event. When I set the fontsize twice in the method, the OnPaint-event is called repeatedly.

To see for yourself, try this:

  1. Create a new VCL Forms application
  2. Place a paintbox on the form
  3. Put the following code in the OnPaint-event:
procedure TForm1.PaintBox1Paint(Sender: TObject);
begin
  PaintBox1.Canvas.MoveTo(random(PaintBox1.Width),random(PaintBox1.Height));
  PaintBox1.Canvas.LineTo(random(PaintBox1.Width),random(PaintBox1.Height));

  PaintBox1.Font.Size := 10; 
  PaintBox1.Font.Size := 12; 
end;

When you run the application you will see a line "jumping" around on the paintbox. However, if you remove one or both of the lines setting the fontsize, you will see a single, stationary line.

Why does this happen, and what can I do to work around it?

1

1 Answers

7
votes

Set PaintBox1.Canvas.Font.Size instead of PaintBox1.Font.Size and your problem will be solved.

As for why it happens: Changing the font property of a control will cause it to be invalidated and redraw, and doing this in the event that does the redrawing causes an infinite loop. Luckily paint events are synthesized and have lower priority than other messages, otherwise your program would hang.