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

如何在AutoIt中检测窗口的大小调整与位置移动?

解决AutoIt窗口移动/大小变化检测问题

你的代码核心问题是仅在循环启动前获取了一次窗口位置,循环内没有持续检测并对比位置/尺寸变化。以下是修改后的完整代码,实现窗口移动或大小调整的检测:

#include <ButtonConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#Region ### START Koda GUI section ### Form=
$Form1 = GUICreate("Form1", 195, 47, 192, 124, BitOR($WS_SIZEBOX, $WS_SYSMENU))
$Button1 = GUICtrlCreateButton("OK", 16, 8, 75, 25)
$Button2 = GUICtrlCreateButton("CANCEL", 104, 8, 75, 25)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###

AutoItSetOption('WinTitleMatchMode', 2)

Local $aPos[4], $aNewPos[4]
$aPos = WinGetPos($Form1)  ; 初始化获取窗口初始位置和尺寸

While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit
            
        Case $Button1
            MsgBox(0, '', 'Button OK is pressed')
            
        Case $Button2
            MsgBox(0, '', 'Button CANCEL is pressed')
    EndSwitch

    ; 核心检测逻辑
    $aNewPos = WinGetPos($Form1)
    ; 对比位置(x,y)或尺寸(宽高)是否变化
    If $aNewPos[0] <> $aPos[0] Or $aNewPos[1] <> $aPos[1] Or $aNewPos[2] <> $aPos[2] Or $aNewPos[3] <> $aPos[3] Then
        ; 判断是移动还是大小变化
        If $aNewPos[0] <> $aPos[0] Or $aNewPos[1] <> $aPos[1] Then
            MsgBox(0, "检测到变化", "窗口已移动")
        EndIf
        If $aNewPos[2] <> $aPos[2] Or $aNewPos[3] <> $aPos[3] Then
            MsgBox(0, "检测到变化", "窗口大小已调整")
        EndIf
        $aPos = $aNewPos  ; 更新为当前位置,避免重复触发提示
    EndIf

    Sleep(50)  ; 降低循环频率,减少资源占用
WEnd

关键说明:

  • 每次循环都会调用WinGetPos($Form1)获取最新的窗口位置和尺寸
  • 通过对比数组内的四个值(x坐标、y坐标、宽度、高度)判断是否有变化
  • 变化发生后立即更新$aPos,防止同一状态反复触发提示
  • 加入Sleep(50)控制循环频率,避免过度消耗CPU资源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 10:38:14