2017-08-30 51 views
-2

我想弄清楚如何在給定的鼠標位置打開窗體打開,儘管我的顯示器設置。在光標位置打開窗體,德爾福

在窗體的OnCreate事件,我有這樣的:

procedure TSplashScreen.FormCreate(Sender: TObject); 
Var 
    oMousePos: TPoint; 
    nLeft, nTop: Integer; 
begin 
    Scaled := false; 
    PixelsPerInch := Screen.PixelsPerInch; 
    Scaled := true; 
    //Position:=poScreenCenter; 

    //center form for 2nd monitor //zzz 
    if (Screen.MonitorCount > 1) then        //zzz 
    begin 
     GetCursorPos(oMousePos); 
     if (oMousePos.X > Screen.Width) or (oMousePos.X < 0) then 
     begin 
     Self.Position := poDesigned; 
     nLeft := Screen.Monitors[1].Left + Round(Screen.Monitors[1].Width/2) - Round(Self.Width/2); 
     nTop := Screen.Monitors[1].Top + Round(Screen.Monitors[1].Height/2) - Round(Self.Height/2); 
     Self.Left := nLeft; 
     Self.Top := nTop; 
     end; 
    end; 
end; 

當我有2臺顯示器,和監控器1被設定爲主監視器,表單將在鼠標光標打開。

但是,如果我設置監測2至小學,窗體將始終顯示器上打開2.

+1

'Mouse.CursorPos'應該已經擁有你需要沒有任何計算的準確位置......而且,你是什麼形式的'Position'設置? –

+1

這裏有很多奇怪的東西。使用Scaled和PixelsPerInch混淆真的很奇怪。當顯示器延伸時僅查看光標位置是奇數。對Screen.Width和零進行測試很奇怪。假設監視器號碼1在某種程度上特別奇怪。使用浮點而不是整數算術很奇怪。你究竟在做什麼?至於這個有很多問題的代碼,爲什麼你選擇不調試它?我無法強調調試技能的重要性。請學習它。如果代碼行爲不如預期,請不要放棄代碼。調試。 「 –

+0

」這在主窗體的初始化部分被調用。「我當然不希望。 'initial'節沒有任何形式的上下文。該部分在任何表單創建之前執行。 –

回答

5

如果你只是想以定位相同的監視器鼠標光標是目前在窗體上,使用Win32 API MonitorFromPoint()功能(這是由VCL的TScreen.MonitorFromPoint()方法包裹),例如:

procedure TSplashScreen.FormCreate(Sender: TObject); 
var 
    r: TRect; 
begin 
    if (Screen.MonitorCount > 1) then 
    begin 
    r := Screen.MonitorFromPoint(Mouse.CursorPos).WorkareaRect; 
    Self.Position := poDesigned; 
    Self.Left := r.Left + ((r.Width - Width) div 2); 
    Self.Top := r.Top + ((r.Height - Height) div 2); 
    { alternatively: 
    Self.SetBounds(
     r.Left + ((r.Width - Width) div 2), 
     r.Top + ((r.Height - Height) div 2), 
     Width, Height); 
    } 
    end else begin 
    Self.Position := poScreenCenter; 
    end; 
end; 
+0

完美!並感謝不要抨擊我繼承的可怕代碼! –