delphi中edit控件内容上下居中
关于delphi中edit控件内容上下居中问题,在网上找了很多,大多介绍的是左右居中,edit左右居中在delphi的高版本里已经增加了一个Alignment属性,设置为taCenter即可,最终在网上找到了上下居中的解决办法,在type加入如下代码:
type
TEdit = class(StdCtrls.TEdit)
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure KeyPress(var Key: Char); override;
procedure WMSize(var msg: TWMSize);message WM_SIZE;
procedure SetParent(AParent: TWinControl);override;
procedure SetCenter;
end;
TEdit = class(StdCtrls.TEdit)
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure KeyPress(var Key: Char); override;
procedure WMSize(var msg: TWMSize);message WM_SIZE;
procedure SetParent(AParent: TWinControl);override;
procedure SetCenter;
end;
然后在程序代码中分别加入以下过程代码:
procedure TEdit.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.Style := Params.Style or ES_MULTILINE;
end;
procedure TEdit.KeyPress(var Key: Char);
begin
inherited;
if Key = #13 then
key := #0;
end;
procedure TEdit.SetCenter;
var
DC: HDC;
SaveFont: HFont;
Sin: Integer;
SysMetrics, Metrics: TTextMetric;
Rct: TRect;
begin
DC := GetDC(0);
GetTextMetrics(DC, SysMetrics);
SaveFont := SelectObject(DC, Font.Handle);
GetTextMetrics(DC, Metrics);
SelectObject(DC, SaveFont);
ReleaseDC(0, DC);
if Ctl3D then Sin := 8 else Sin := 6;
Rct := ClientRect;
Sin := Height - Metrics.tmHeight - Sin;
Rct.Top := Sin div 2;
SendMessage(Handle, EM_SETRECT, 0, Integer(@Rct));
end;
procedure TEdit.SetParent(AParent: TWinControl);
begin
inherited;
if Parent <> nil then
begin
SetCenter;
end;
end;
procedure TEdit.WMSize(var msg: TWMSize);
begin
inherited;
SetCenter;
end;
begin
inherited;
Params.Style := Params.Style or ES_MULTILINE;
end;
procedure TEdit.KeyPress(var Key: Char);
begin
inherited;
if Key = #13 then
key := #0;
end;
procedure TEdit.SetCenter;
var
DC: HDC;
SaveFont: HFont;
Sin: Integer;
SysMetrics, Metrics: TTextMetric;
Rct: TRect;
begin
DC := GetDC(0);
GetTextMetrics(DC, SysMetrics);
SaveFont := SelectObject(DC, Font.Handle);
GetTextMetrics(DC, Metrics);
SelectObject(DC, SaveFont);
ReleaseDC(0, DC);
if Ctl3D then Sin := 8 else Sin := 6;
Rct := ClientRect;
Sin := Height - Metrics.tmHeight - Sin;
Rct.Top := Sin div 2;
SendMessage(Handle, EM_SETRECT, 0, Integer(@Rct));
end;
procedure TEdit.SetParent(AParent: TWinControl);
begin
inherited;
if Parent <> nil then
begin
SetCenter;
end;
end;
procedure TEdit.WMSize(var msg: TWMSize);
begin
inherited;
SetCenter;
end;
运行后,界面上的edit内容均上下居中了。