Link to home
Start Free TrialLog in
Avatar of julianpointer
julianpointer

asked on

Resize a richedit control

I want to resize a richedit control so that all the text in the control is shown. ie as you type in the control it automatically increases/descreses size.

someting like richedit1.Height := round(richedit1.Lines.Count * 13.5);

this dosn't work properly, I need to get the logical client area ?

Avatar of Cynna
Cynna

julianpointer,

Line height is font height+external leading. BUT, you
also have to account for constant offset, consisting of
additional spacing and bevel of top/bottom edges of TRichEdit.

For example (copy/paste):

procedure TForm1.ResizeRichEdit;
var TM : TTextMetric;
    Offset: Integer;
begin
  Offset:=8;
  with RichEdit1 do begin
    GetTextMetrics(Canvas.Handle, TM);
    Height := Lines.Count * (TM.tmHeight + TM.tmExternalLeading) + Offset;
  end;
end;


If you want this to happen automatically, probably the easiest
would be placing it in OnResizeRequest event:

procedure TForm1.RichEdit1ResizeRequest(Sender: TObject; Rect: TRect);
begin
  ResizeRichEdit;
end;
Also, if you're bothered with auto-scroll on Enter,
this is improved version that takes care of it:

var OldLineCount: Integer; // global var

(....)

procedure TForm1.ResizeRichEdit(VSize: Integer);
var TM : TTextMetric;
    Offset: Integer;
begin
  Offset:=8;
  with RichEdit1 do begin
    GetTextMetrics(Canvas.Handle, TM);
    Height := VSize * (TM.tmHeight + TM.tmExternalLeading) + Offset;
  end;
end;

procedure TForm1.RichEdit1ResizeRequest(Sender: TObject; Rect: TRect);
// improved event handler
var s: String;
    CurrentLineCount: Integer;
begin
  RichEdit1.OnResizeRequest:=nil;
    s:=RichEdit1.Text;
    if s<>'' then begin
       CurrentLineCount:=RichEdit1.Lines.Count;
       if s[length(s)]=Chr(10) then Inc(CurrentLineCount);
       if (CurrentLineCount<>OldLineCount) then ResizeRichEdit(CurrentLineCount);
       OldLineCount:=CurrentLineCount;
    end;
  RichEdit1.OnResizeRequest:=RichEdit1ResizeRequest;
end;
Avatar of julianpointer

ASKER

Two Issues,
  1. When you alter the font size.
  2. When you scroll off the bottom of the screen you lose the caret.
ASKER CERTIFIED SOLUTION
Avatar of Cynna
Cynna

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial