[英]Delphi - Open window at location of a TLabel
我有兩種形式,即Form1和Form2。在Form1上有一個TLabel,它的onclick事件調用Form2.show。
我想做的是,如果弄清楚如何使form2在標簽中間居中的標簽下方顯示5px :) Form2很小,只顯示了一些選項。
我可以使用鼠標位置,但還不夠好。
我在想類似
// Set top - add 20 for the title bar of software
Form2.Top := Form1.Top + Label1.Top + Label1.Height + 20;
// Set the Left
Form2.Left := Form1.Left + Label1.Left + round(Label1.Width / 2) - round(form2.Width/2);
但我認為有更好的方法
您需要使用Form2
的父級坐標系為其設置坐標。 假設“父級”為桌面(因為您要補償標題欄的高度),可以這樣做:
procedure ShowForm;
var P: TPoint;
begin
// Get the top-left corner of the Label in *screen coordinates*. This automatically compensates
// for whatever height the non-client area of the window has.
P := Label1.ScreenToClient(Label1.BoundsRect.TopLeft);
// Assign the coordinates of Form2 based on the translated coordinates (P)
Form2.Top := P.Y + 5; // You said you want it 5 pixels lower
Form2.Left := P.X + 5 + (Label1.Width div 2); // Use div since you don't care about the fractional part of the division
end;
您需要根據居中要求調整代碼以適應Form2的位置,但我不太了解您想要什么。 當然,如果框架或面板夠用,那就更好了! 仔細看看Guillem的解決方案。
procedure TForm2.AdjustPosition(ARefControl: TControl);
var
LRefTopLeft: TPoint;
begin
LRefTopLeft := ARefControl.ScreenToClient(ARefControl.BoundsRect.TopLeft);
Self.Top := LRefTopLeft.Y + ARefControl.Height + 5;
Self.Left := LRefTopLeft.X + ((ARefControl.Width - Self.Width) div 2);
end;
然后,您可以使窗體相對於任何所需控件進行調整,如下所示:
Form2.AdjustPosition(Form1.Label1);
您真的需要Form2成為表單嗎? 您可以選擇創建一個包含Form2邏輯的框架,並使用隱藏的TPanel作為其父級。 當用戶單擊Label1時,將顯示面板。
像下面這樣。 當您創建Form1或單擊Label1時(取決於您的需要):
Frame := TFrame1.Create(Self);
Frame.Parent := Panel1;
在Label1的OnClick事件中:
Panel1.Top := Label1.Top + 5;
Panel1.Left := Label1.Left + round(Label1.Width / 2) - round(form2.Width/2);
Panel1.Visible := true;
用戶完成操作后,只需再次隱藏面板即可(必要時銷毀框架)。 如果您在用戶使用Form1時使Frame保持活動狀態,請記住在離開表單時將其釋放。
高溫超導
ClientOrigin
屬性將返回屏幕坐標中lebel的左上角,因此您無需手動確定它:
var
Pt: TPoint;
begin
Pt := Label1.ClientOrigin;
Form2.Left := Pt.X + Round(Label1.Width / 2) - Round(Form2.Width/2);
Form2.Top := Pt.Y + Label1.Height + 5;
end;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.