stanleyxu2005
stanleyxu2005

Reputation: 8241

Delphi: How to adjust text vertical position of a TEdit

The text in a TEdit (or TCombo, TButtonedEdit) is always aligned to top. I have not found any property to change the alignment. Usually it is not a problem, unless I want to set a larger height.

I googled a little. There are solutions to adjust the left and the right margins by sending a Windows message. But I have no idea, how to adjust the vertical alignment.

I do not want to use a larger font. Any ideas?

Upvotes: 6

Views: 7759

Answers (3)

Mahan
Mahan

Reputation: 163

... Any ideas?

Unfortunately I found no good solution for that and I had to use a trick in my project: The trick is, that I place a shape under the edit!

Simply set the AutoSize of your TEdit to False, place and change the width and height of the TEdit as desired and then use the following procedure:

procedure PutShapeUnderEdit(edit: TEdit; padding: Integer);
var
  bmp: TBitmap;
  shape: TShape;
  h: Integer;
begin
  bmp := TBitmap.Create;
  try
    bmp.Canvas.Font.Assign(edit.Font);
    h := bmp.Canvas.TextExtent('Some characters: AÄBCDEgjpqy!"$&/|,').cy;
  finally
    bmp.Free;
  end;
  shape := TShape.Create(nil);
  shape.Parent := edit.Parent;
  shape.Brush.Color := edit.Color;
  shape.Pen.Color := edit.Font.Color;
  shape.Left := edit.Left;
  shape.Top := edit.Top;
  shape.Width := edit.Width;
  shape.Height := edit.Height;
  edit.BorderStyle := bsNone;
  edit.Left := edit.Left + padding;
  edit.Width := edit.Width - 2 * padding;
  edit.Top := edit.Top + padding + (edit.Height - h - 2 * padding) div 2;
  edit.Height := h;
end;

To use it just call the procedure one time in FormCreate:

procedure TForm1.FormCreate(Sender: TObject);
begin
  PutShapeUnderEdit(Edit1, 10);
end;

The output

This works for me but you must consider other parameters in your project and do not use this code blindly, just see if the idea works for you.

By the way, I'm using VCL in Delphi 10 Seattle and Windows 10

Upvotes: 0

Lars
Lars

Reputation: 1438

Dusting of an old question... I found a solution in a similar c++ question: https://stackoverflow.com/a/51079348/2107791

  • The text gets automatically vertically centred by setting TEdit's property BorderStyle to bsSingle.
  • The trade-off is a border around the Edit box

Works for me using Delphi 10.3 Rio.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 613572

If there was such an option it would be applied by way of a style. The EDIT control styles list contains no such style and so the conclusion is that the underlying control does not offer this functionality.

You'll have to either make a new control, or take over the painting yourself. Neither is particularly appealing.

Upvotes: 3

Related Questions