Recent

Author Topic: Center the text vertically in a TEdit  (Read 472 times)

pmesquita

  • Jr. Member
  • **
  • Posts: 62
Center the text vertically in a TEdit
« on: June 28, 2022, 04:08:23 am »
Guys,
Is there any way to center the text vertically in a TEdit without the borders (BorderStyle=bsnone) ?
Because without the borders the text is always on top of the control...
I've been reading that the Windows message WM_NCCALCSIZE changes the internal area of TEdit but this message is simply not sent to TEdit..

Windows Message Post
https://forum.lazarus.freepascal.org/index.php?topic=24595.0

ASerge

  • Hero Member
  • *****
  • Posts: 2223
Re: Center the text vertically in a TEdit
« Reply #1 on: June 28, 2022, 07:15:28 pm »
Is there any way to center the text vertically in a TEdit without the borders (BorderStyle=bsnone) ?
It's easier to put TEdit on a TPanel with a clWindow color without borders and the desired size. And then vertically align TEdit inside TPanel.
Code: Pascal  [Select][+][-]
  1. uses Windows;
  2.  
  3. procedure VCenterControlInsideParentByTextHeight(Control: TWinControl);
  4.  
  5.   function GetWindowTextHeight(Wnd: HWND): Integer;
  6.   var
  7.     DC: HDC;
  8.     TM: TTextMetric;
  9.   begin
  10.     DC := GetWindowDC(Wnd);
  11.     try
  12.       if not GetTextMetrics(DC, TM) then
  13.         RaiseLastOSError;
  14.     finally
  15.       ReleaseDC(Wnd, DC);
  16.     end;
  17.     Result := TM.tmHeight;
  18.   end;
  19.  
  20. var
  21.   R: TRect;
  22.   Extra: Integer;
  23. begin
  24.   R := Control.BoundsRect;
  25.   Extra := R.Height - GetWindowTextHeight(Control.Handle);
  26.   if Extra <= 0 then
  27.     Exit;
  28.   R.Inflate(0, -Extra div 2);
  29.   Control.BoundsRect := R;
  30. end;
  31.  
  32. procedure TForm1.Button1Click(Sender: TObject);
  33. begin
  34.   VCenterControlInsideParentByTextHeight(Edit1);
  35. end;

 

TinyPortal © 2005-2018