How to calculate the line length of a TRichEdit (Views: 100)


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.


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.

function MakeLine(re: TRichEdit; ch: Char): string;
  cv: TControlCanvas;
  r: TRect;
  max, len: Integer;
  cv := TControlCanvas.Create;
    cv.Control := re;
    re.Perform(EM_GETRECT, 0, lparam(@r));
    max := r.right - r.Left;
    len := max div cv.TextWidth(ch);
    Result := StringOfChar(ch, len);
    while cv.TextWidth(result) > max do
      Delete(result, Length(Result), 1);

procedure TForm1.Button1Click(Sender: TObject);
  richedit1.SelText := MakeLine(richedit1, '-');

You may want to enhance this to take account of any margin settings in the current paragraph.

<< Back to main page