2012-06-20 69 views
2

可能重复:
Can I make a TMemo size itself to the text it contains?自动调整备忘录

需要做自动调整备忘录:高度和宽度。

我自动调整高度如下:

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; 

但我不知道该怎么做自动调整宽度。我有一个想法:如果滚动条被激活,然后增加宽度,直到它变为不活动,但我不知道如何实现。

+2

Austosizing只能在一个方向上实现。要么固定高度并调整宽度或固定宽度并调整高度。 – hubalu

+0

@SimaWB,我需要,并在宽度和高度。 +字体可以不同! – dedoki

回答

3

不是最好的解决方案,但它的工作原理:

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; 

并添加以下代码Memo1.Onchange事件的结束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; 
+0

我猜不到使用该标签。谢谢! – dedoki

+2

等待,您将实例化TLabel以获取外部控件的文本宽度。天啊... – TLama