How to centre text in a TEdit #85

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