简体   繁体   English

在光标位置打开表格,Delphi

[英]Open form at cursor position, Delphi

I am trying to figure out how to position a Form to open at a given mouse location, despite my monitor settings. 尽管我进行了显示器设置,但我试图弄清楚如何将窗体放置在给定的鼠标位置处。

In the Form's OnCreate event, I have this: 在窗体的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;

When I have 2 monitors, and monitor 1 is set as primary monitor, the Form will open at the mouse cursor. 当我有2个监视器,并且将监视器1设置为主监视器时,该窗体将在鼠标光标处打开。

However, if I set monitor 2 to primary, the Form will always open on monitor 2. 但是,如果将监视器2设置为主监视器,则该窗体将始终在监视器2上打开。

If you just want to position the Form on the same monitor that the mouse cursor is currently in, use the Win32 API MonitorFromPoint() function (which is wrapped by the VCL's TScreen.MonitorFromPoint() method), eg: 如果您只想将Form放在鼠标光标当前所在的同一监视器上,请使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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