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

MacOS中AppleScript无法访问多实例MATLAB App Designer独立应用窗口

问题:无法通过AppleScript控制两个MATLAB打包的独立应用窗口

环境信息

  • 系统:MacOS Catalina 10.15.7(2012款后期MacBook Pro)
  • MATLAB版本:R2022b学术版
  • 打包应用:
    • m_app1.app(窗口标题:app_a)
    • m_app2.app(窗口标题:app_b)

问题现象

  • 两个应用同时运行时,AppleScript仅能正常访问先启动的实例,尝试操作第二个实例时触发错误:

    System Events encountered an error: cannot retrieve window "app_b" of application process "MATLABWindow".

  • 启动每个应用后,Dock会生成两个图标:
    • 一个以应用名命名(始终最小化,点击无反应)
    • 另一个为MATLABWindow(对应实际可操作的应用窗口)
  • 通过Accessibility Inspector确认两个窗口的AX属性均正常存在,但AppleScript无法获取第二个窗口的属性

已尝试操作

  • 获取两个MATLABWindow进程的[id, unix id],尝试通过PID访问第二个窗口,仍无效,仅能操作先启动的实例
  • 遍历所有可见窗口,仅能读取先启动窗口的属性,读取第二个窗口属性时触发错误

解决方案

核心思路

MATLAB打包的独立应用通过MATLABWindow进程托管窗口,直接访问进程的windows集合会存在进程隔离限制,因此需要通过遍历进程的UI元素,直接匹配窗口的AXTitle属性来定位目标窗口。

实现脚本

以下AppleScript可根据指定窗口标题,实现前置、最大化/最小化操作:

-- 设置目标窗口的标题(替换为app_a或app_b)
set targetWindowTitle to "app_b"

tell application "System Events"
    -- 遍历所有MATLABWindow进程
    repeat with p in every process where name is "MATLABWindow"
        try
            -- 获取进程的根UI元素
            set appRootElement to UI element 1 of p
            -- 查找匹配标题的窗口元素
            set targetWindows to (UI elements of appRootElement whose role description is "window" and value of attribute "AXTitle" is targetWindowTitle)
            
            if targetWindows is not {} then
                set targetWindow to item 1 of targetWindows
                
                -- 操作1:将窗口设为前置(获得焦点)
                set value of attribute "AXFocused" of targetWindow to true
                
                -- 操作2:最大化窗口(全屏模式)
                set value of attribute "AXFullScreen" of targetWindow to true
                
                -- 操作3:最小化窗口(取消注释即可启用)
                -- set value of attribute "AXMinimized" of targetWindow to true
                
                exit repeat -- 找到目标窗口后退出循环
            end if
        on error errMsg
            -- 忽略无法访问的进程,继续遍历下一个
            log errMsg
        end try
    end repeat
end tell

注意事项

  1. 确保脚本编辑器/终端已被授予辅助功能权限:
    • 打开「系统偏好设置」→「安全性与隐私」→「隐私」→「辅助功能」
    • 添加运行脚本的应用(如脚本编辑器、终端)
  2. 运行脚本前,关闭其他无关的MATLABWindow进程(如MATLAB主程序、App Designer),避免干扰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 02:44:57