Author: Jonas Bilinkevicius
I want to fill a whole line with the same char in a TRichEdit but I can't figure
out how I could retrieve the maximum char number for a line.
Answer:
The number of characters you would be able to fit into a line depends on the font
and the character used (unless the font is fixed-pitch). The first order of the day
is to find out how much space is available for the line. This you do by asking the
control for its formatting rectangle, which is usually a bit smaller than the
client area. Then you determine the font to use and measure the character, which
gives you a first estimate of the number of characters that may fit. You construct
a string of this character of the calculated length and measure it again. It may
turn out to be too long since the length also includes intercharacter distance, so
you remove characters till it fits.
1 2 function MakeLine(re: TRichEdit; ch: Char): string;
3 var4 cv: TControlCanvas;
5 r: TRect;
6 max, len: Integer;
7 begin8 cv := TControlCanvas.Create;
9 try10 cv.Control := re;
11 cv.Font.Assign(re.SelAttributes);
12 re.Perform(EM_GETRECT, 0, lparam(@r));
13 max := r.right - r.Left;
14 len := max div cv.TextWidth(ch);
15 Result := StringOfChar(ch, len);
16 while cv.TextWidth(result) > max do17 Delete(result, Length(Result), 1);
18 finally19 cv.Free;
20 end;
21 end;
22 23 procedure TForm1.Button1Click(Sender: TObject);
24 begin25 richedit1.SelText := MakeLine(richedit1, '-');
26 end;
You may want to enhance this to take account of any margin settings in the current paragraph.