In my applications there are many cases when I have several groups of TLabel followed by a TEdit on my Forms, you know... when some properties needs to be edited. I want to align vertically those controls so that their font baseline will be on the same line. I need to do this at runtime, after I scale the Form and everything is messed up. Do yo know if there is a way to do that ? I saw that Delphi IDE does it verry easy at design time...
Edit: I managed to get the position of the baseline relative to font margins, with GetTextMetrics but now I don't know where the font Top is positioned in the control client area (TLabel and TEdit)...
CodePudding user response:
This is the code that aligns a TLabel to a TEdit... I don't know if it covers all the cases, but what I've tried so far has worked perfectly. I will try tomorow other controls too...
procedure AlignLabelToEdit(ALabel: TLabel; AEdit: TEdit);
var DC: HDC;
SaveFont: HFont;
LBL, EBL, B: Integer;
LM, EM: TTextMetric;
begin
DC:= GetDC(0);
try
SaveFont:= SelectObject(DC, ALabel.Font.Handle);
GetTextMetrics(DC, LM);
SelectObject(DC, AEdit.Font.Handle);
GetTextMetrics(DC, EM);
SelectObject(DC, SaveFont);
finally
ReleaseDC(0, DC);
end;
if ALabel.Layout = tlTop then LBL:= LM.tmAscent
else if ALabel.Layout = tlBottom then LBL:= ALabel.Height - LM.tmDescent
else LBL:= ((ALabel.Height - LM.tmHeight) div 2 LM.tmAscent);
B:= GetSystemMetrics(SM_CYEDGE);
EBL:= EM.tmAscent;
if AEdit.BorderStyle = bsSingle then Inc(EBL, B 1);
ALabel.Top:= AEdit.Top (EBL-LBL);
end;
CodePudding user response:
Have you considered putting the labels above the edit boxes (or using TLabeledEdit instead)? Not only does that make aligning them easier, it also covers the case of translations (e.g. of label captions) that are much longer in some languages than they are in English.
