繁体   English   中英

Delphi-在TLabel位置打开的窗口

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM