如何让TEDIT控件的宽度和其文本的长度一样?(20分)

H

hongsen

Unregistered / Unconfirmed
GUEST, unregistred user!
如何让TEDIT控件的宽度和其文本的长度一样?
如下代码为何出错?(错误:吃掉一个字符)
procedure TmyEdit.EditChange(Sender: TObject);
var lpSize:Tsize;
strpt:pchar;
begin
strpt:=pchar(text);
GetTextExtentPoint32(

getdc(handle), // handle of device context
@strpt, // address of text string
GetTextLen, // number of characters in string
lpSize // address of structure for string size
);
width:=lpSize.cx;
if width=0 then
width:=2;
end;
 
cx 8,16,20,32,36,44,52,66一点规律都没有。:-<
试一下:
Edit1.Width:=Edit1.Font.Size*Edit1.GetTextLen+5;
 
用drawtext可以取得字符串的长度和宽度。
var
dc: hdc;
s: string;
r: trect;
h: integer;
begin
s:=edit1.text;
dc:=getdc(edit1.handle);
r:=rect(2,2,4,4)
h:=drawtext(dc, pchar(s),r, DT_CALCRECT or DT_SINGLELINE);
edit1.height:=h+4;
edit1.width:=r.right+2;
deletedc(dc);
end;
 
我想你可以参考source中的TLabel或TStaticText的AutoSize是怎么做的,
下面是TCustomStaticText的做法:
Edit.Width:=lpSize.cx+GetSystemMetrics(SM_CXBORDER) * 4;
//加上窗口的边界,为何是四倍就不知道了,可能和边界还要留点空,
//如果你的Edit的Ctl3D为True,还要加上几倍,我试下来8倍的效果挺好
 
chenke,o-o,Another_eYes 的方法对于保证长度都可以,我忘了在问题中详细说明问题,问题中所说的吃掉一个字符是指在TEDIT的ONCHANGE事件中发生的,我希望在ONCHANGE事件中改变长度。
 
把 Edit1.Width:=Edit1.Font.Size*Edit1.GetTextLen+5;加到ONCHANGE事件中
 
chenke先生试过没有?
 
我就是放在Onchange中试的呀!
 
多人接受答案了。
 

Similar threads

S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
I
回复
0
查看
724
import
I
顶部