2011-03-27 75 views
0

我有兩種形式,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

回答

1

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; 
2

你真的需要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

3

你需要使用的座標系是家長設置的座標爲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的解決方案。

3
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