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

如何使用Hammerspoon模拟点击macOS窗口或弹窗中的指定按钮

Hammerspoon 模拟点击弹窗按钮实现方案

方案1:坐标点击(最简单,适合固定位置的弹窗)

直接指定按钮的屏幕坐标触发点击,实现成本最低,适合弹窗位置固定的场景:

  • 先获取目标按钮的坐标:将鼠标移到按钮上,在Hammerspoon控制台执行hs.printf("%s", hs.inspect(hs.mouse.getAbsolutePosition()))即可输出当前坐标
  • 点击代码示例:
-- 直接点击指定坐标,不需要提前移动鼠标
hs.mouse.leftClick({x=替换为你的按钮x坐标, y=替换为你的按钮y坐标})

-- 需移动鼠标的场景,加10ms延迟避免点击失效
hs.mouse.absolutePosition({x=100, y=200})
hs.timer.usleep(10000)
hs.mouse.leftClick()

方案2:无障碍接口点击(更稳定,无需移动鼠标)

通过macOS原生无障碍接口直接触发按钮点击,不需要改动鼠标位置,弹窗不在前台也能触发,是更推荐的方案。
前置要求:先在 macOS 系统设置「隐私与安全性 - 辅助功能」中给 Hammerspoon 开启权限。

点击弹窗自带的关闭按钮

-- 可以替换为你要定位的特定窗口,这里用当前最前置窗口做示例
local targetWindow = hs.window.frontmostWindow()
if not targetWindow then return end

local axWindow = hs.axuielement.windowElement(targetWindow)
local closeButton = axWindow:attributeValue("AXCloseButton")
if closeButton then
    -- 直接触发按钮点击动作
    closeButton:performAction("AXPress")
else
    -- 未找到关闭按钮时可以兜底走坐标点击逻辑
    hs.mouse.leftClick({x=坐标x, y=坐标y})
end

点击弹窗内自定义按钮(如确认、取消等)

如果需要点击弹窗内带文字的自定义按钮,可以遍历窗口的无障碍元素匹配按钮标题后触发点击:

local targetWindow = hs.window.frontmostWindow()
if not targetWindow then return end

local axWindow = hs.axuielement.windowElement(targetWindow)
-- 搜索窗口内所有按钮元素
local allButtons = axWindow:elementSearch({
    callback = function(element)
        return element:attributeValue("AXRole") == "AXButton"
    end
})

-- 匹配按钮标题后点击,可替换为你要找的按钮文字
for _, button in ipairs(allButtons) do
    local buttonTitle = button:attributeValue("AXTitle")
    if buttonTitle == "取消" then
        button:performAction("AXPress")
        break
    end
end

注意事项

  • 定位特定APP的弹窗时,可以用hs.application.find("你的APP名称")先拿到APP对象,再遍历APP的所有窗口匹配弹窗标题,不用依赖窗口前置,稳定性更高
  • 若偶尔出现点击失效,可以在操作前加5-20ms的延迟,用hs.timer.usleep(5000)即可,参数单位为微秒

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:57:02