Question

Possible Duplicate:
Can I make a TMemo size itself to the text it contains?

Need to do autosize memo: height and width.

I autosize the height as follows:

function TForm1.AutoSizeMemoY(Memo: TMemo): word;
begin
  Canvas.Font := Memo.Font;
  Result := Canvas.TextExtent(Memo.Lines.Strings[0]).cy * Memo.Lines.Count +
    Canvas.TextExtent(Memo.Lines.Strings[0]).cy;
end;

But I do not know how to do autosize the width. I have an idea: if the scrollbar is activated, then increase the width until it becomes inactive, but I do not know how to implement that.

Was it helpful?

Solution

Not the best solution but it works:

function GetTextWidth(F: TFont; s: string): integer;
var
  l: TLabel;
begin
  l := TLabel.Create(nil);
  try
    l.Font.Assign(F);
    l.Caption := s;
    l.AutoSize := True;
    result := l.Width + 8;
  finally
    l.Free;
  end;
end;

And add following code to the end of Memo1.Onchange event in this answer

  LineInd := Memo1.Perform(EM_LINEFROMCHAR, Memo1.SelStart, 0);//focused Memo1 line Index
  Wd := GetTextWidth(Memo1.Font, Memo1.Lines[LineInd]);
  //MaxWidthLineInd = index of the line which has the largest width. 
  //Init value of MaxWidthLineInd = 0
  if MaxWidthLineInd = LineInd then 
    Memo1.Width := Wd
  else begin
    if Wd > Memo1.Width then
    begin
      Memo1.Width := Wd;
      MaxWidthLineInd := LineInd;
    end;
  end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top