«« Site Rescued »»

While the site is still going to move from its current host, a new site will now take its place. More Info.

The new site may have less content, but the core will now remain. And it will now play nicely with phones! Keep an eye on the DelphiDabbler Blog for news.

» Help

How to centre text in a TEdit

   

You need to create your own class with an Alignment property:

{ ... }
  TMyEdit = Class(TEdit)
  private
    FAlignment: TAlignment;
    procedure SetAlignment(Value: TAlignment);
  protected
    procedure KeyPress(var Key: Char); override;
    procedure CreateParams(var Params: TCreateParams); override;
  published
    property Alignment: TAlignment read FAlignment write SetAlignment;
  end;

procedure TMyEdit.CreateParams(var Params: TCreateParams);
begin
  inherited CreateParams(Params);
  case Alignment of
    taLeftJustify:
      Params.Style := Params.Style or ES_LEFT and not ES_MULTILINE;
    taRightJustify:
      Params.Style := Params.Style or ES_RIGHT and not ES_MULTILINE;
    taCenter:
      Params.Style := Params.Style or ES_CENTER and not ES_MULTILINE;
  end;
end;

procedure TMyEdit.SetAlignment(Value: TAlignment);
begin
  if FAlignment <> Value then
  begin
    FAlignment := Value;
    RecreateWnd;
  end;
end;

Also see Tip #159 for an alternative approach.

Original resource: The Delphi Pool
Author: Steve Zimmelman
Added: 2009-08-24
Last updated: 2010-04-08

« Return to contents »