You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取活动显示器宽高并让AutoHotkey GUI在其居中显示?

让AutoHotkey GUI在活动显示器居中显示

原始代码

#singleinstance, force
#Warn, All, OutputDebug

space::
Gui HUD:New, +AlwaysOnTop +ToolWindow -Caption +HwndMainHwnd, hudWin
Gui HUD:Font,s14,Consolas
Gui, Add, Text,,% Clipboard
GuiControlGet, OutputVar, Pos, Static1
Gui HUD:Show

Return

问题需求

上述程序用于显示剪贴板内容,当前默认在主显示器生成GUI,需要修改为在**活动显示器(拥有活动窗口或键盘焦点的屏幕)**居中显示,适配三台显示器的场景。

解决方案

核心思路是先定位活动窗口所在的显示器,再计算GUI在该显示器的居中坐标,修改后的完整代码如下:

#singleinstance, force
#Warn, All, OutputDebug

space::
    ; 获取活动窗口的位置信息
    WinGetActiveStats, Title, Width, Height, X, Y
    ; 根据窗口坐标获取对应显示器的边界参数
    SysGet, Monitor, Monitor, %X%, %Y%
    
    ; 创建GUI并设置内容
    Gui HUD:New, +AlwaysOnTop +ToolWindow -Caption +HwndMainHwnd, hudWin
    Gui HUD:Font,s14,Consolas
    Gui, Add, Text,, %Clipboard%
    ; 获取文本控件的实际尺寸
    GuiControlGet, OutputVar, Pos, Static1
    GuiWidth := OutputVarW
    GuiHeight := OutputVarH
    
    ; 计算活动显示器的中心位置坐标
    CenterX := MonitorLeft + (MonitorRight - MonitorLeft - GuiWidth) // 2
    CenterY := MonitorTop + (MonitorBottom - MonitorTop - GuiHeight) // 2
    
    ; 在计算好的位置显示GUI
    Gui HUD:Show, x%CenterX% y%CenterY%
Return

关键步骤说明

  • WinGetActiveStats:获取当前活动窗口的标题、尺寸和位置坐标,通过窗口的X/Y值确定它所在的显示器
  • SysGet, Monitor, Monitor, %X%, %Y%:根据传入的窗口坐标,自动获取对应显示器的边界参数(MonitorLeft/MonitorRight/MonitorTop/MonitorBottom),该命令支持任意数量的显示器,无需手动指定主副屏
  • 居中坐标计算:用显示器的有效宽度(MonitorRight - MonitorLeft)减去GUI宽度,取一半后加上显示器左偏移;高度同理,最终得到GUI左上角的居中坐标
  • 特殊情况处理:如果当前激活的是桌面(无活动窗口),WinGetActiveStats会获取桌面窗口的信息,同样能正确定位到鼠标所在的显示器

内容的提问来源于stack exchange,提问作者Ralf_Reddings

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 08:17:29