Delphi的光标位置开放形式



尽管我的监视器设置了,但我还是试图弄清楚如何在给定鼠标位置打开表格。

在表格的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个显示器,并且将监视器设置为主监视器时,该表格将在鼠标光标处打开。

但是,如果我将Monitor 2设置为主,则表格将始终在Monitor 2上打开。

如果您只想将表单放置在鼠标光标当前所在的同一监视器上,请使用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;

最新更新