Setting the fontsize of a Paintbox causes OnPaint to be called
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:
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?
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.
链接地址: http://www.djcxy.com/p/60462.html