秋·风

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  278 随笔 :: 0 文章 :: 308 评论 :: 20万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
在Lazarus中要实现TEdit组件的文本垂直居中,可以通过自定义TEdit组件并重写其CreateParams方法来设置编辑框的样式为多行,然后通过SetCenter方法来调整文本的垂直位置。
在需要的unit添加EditCenter单元。
注意:EditCenter单元一定要放StdCtrls后面,否则无效果。
复制代码
unit EditCenter;

{$mode ObjFPC}{$H+}

interface

uses
 Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, Messages, LCLType, LCLIntf;

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;

implementation

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.WMSize(var msg: TWMSize);
begin
  inherited;
  SetCenter;
end;

procedure TEdit.SetParent(AParent: TWinControl);
begin
  inherited;
  if Parent <> nil then
  begin
    SetCenter;
  end;
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);
  Rct := ClientRect;
  Sin := Height - Metrics.tmHeight - Sin;
  Rct.Top := Sin div 2;
  SendMessage(Handle, 180, 0, Integer(@Rct));
end;

end.
复制代码

使用范例:

复制代码
unit Unit1;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls,  EditCenter;

type

  { TForm1 }

  TForm1 = class(TForm)
    Button1: TButton;
    Edit1: TEdit;
  private

  public
  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}
           
复制代码

 编译运行的效果:

 这个方面windows和linux都有效。
注意:要设置控件的AutoSize:=false;

posted on   秋·风  阅读(168)  评论(7编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示