Delphi - 在TLabel的位置打开窗口

问题描述:

我有两种形式,Form1和Form2 我在Form1上有一个TLabel,它是一个调用Form2.show的onclick事件;Delphi - 在TLabel的位置打开窗口

我想要做什么,如果弄清楚我怎样才能使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); 

,但我认为可以有更好的办法

+0

为什么20?我认为你应该增加15.或者是30?即:常数不好! – 2011-03-27 09:08:39

+0

@Cosmind:我认为这是他的问题。 – 2011-03-27 10:10:45

ClientOrigin属性将在屏幕坐标返回勒贝尔的左上角,所以你不需要手动确定:

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; 

你真的需要Form2的是一种形式?您可以选择创建一个包含Form2逻辑的框架,并使用隐藏的TPanel作为其父项。当用户点击Label1时,显示面板。

像下面这样的东西。当您创建Form1中或当您单击Label1的(根据您的需要):

Frame := TFrame1.Create(Self); 
Frame.Parent := Panel1; 

在onclick事件的Label1:

Panel1.Top := Label1.Top + 5; 
Panel1.Left := Label1.Left + round(Label1.Width/2) - round(form2.Width/2); 
Panel1.Visible := true; 

当用户刚做再次隐藏面板(和必要时销毁框架)。如果您在用户使用Form1时保持帧处于活动状态,请记住在离开表单时将其释放。

HTH

+0

+1,因为一个框架通常是一个很好的(被忽视的)解决方案。但是也可以使用Form来做一个案例。 – 2011-03-27 09:07:46

你需要使用的坐标系是家长设置的坐标为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; 

你需要适应的代码,窗体2的基础上,定位你的中心要求,我不太明白你想要什么。当然,如果一个框架或面板足够了,那就更好了!仔细看看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); 
+0

用于清洁代码。你可以通过传递参考文献和主题使它适用于任何控制。 AdjustPosition(aForm:TForm,ARefControl:TControl);如果他也有Form3的话 – Najem 2011-03-27 11:35:38