如何在AppleScript运行时禁用Command+Tab,防止跨应用执行?
临时禁用Command+Tab的解决方案
针对你的需求,确实可以在AppleScript执行期间临时禁用Command+Tab组合键,结合你现有的InDesign激活逻辑,提供两种可行实现方案:
方法1:临时修改系统快捷键映射(推荐)
通过System Events修改全局快捷键,把Command+Tab映射到空操作,脚本执行完毕后再恢复原设置。这种方法不会完全拦截按键输入,但会让Command+Tab失去切换应用的功能,直到脚本恢复配置。
完整实现代码
-- 保存当前Command+Tab的快捷键设置 on saveCmdTabShortcut() tell application "System Events" try return value of key binding "AXApplicationSwitcher" of application preferences on error return "" -- 系统默认无自定义设置时返回空 end try end tell end saveCmdTabShortcut -- 禁用Command+Tab(映射为空操作) on disableCmdTab() tell application "System Events" set key binding "AXApplicationSwitcher" of application preferences to "" end tell end disableCmdTab -- 恢复Command+Tab原设置 on restoreCmdTab(originalShortcut) tell application "System Events" if originalShortcut is not "" then set key binding "AXApplicationSwitcher" of application preferences to originalShortcut else -- 若原本无自定义设置,删除我们添加的空配置 delete key binding "AXApplicationSwitcher" of application preferences end if end tell end restoreCmdTab -- 优化后的InDesign激活函数 on ActiveError() global frontApp, frontAppName, windowTitle set windowTitle to "" tell application "System Events" try set frontApp to first application process whose frontmost is true set frontAppName to name of frontApp tell process frontAppName tell (1st window whose value of attribute "AXMain" is true) set windowTitle to value of attribute "AXTitle" end tell end tell on error -- 处理InDesign未打开或无窗口的异常情况 set frontAppName to "" end try end tell if frontAppName is not equal to "Adobe InDesign 2022" then tell application "Adobe InDesign 2022" to activate -- CustomAlert() -- 保留你的自定义弹窗逻辑 end if return {frontAppName, windowTitle} end ActiveError -- 主脚本执行逻辑 set originalShortcut to saveCmdTabShortcut() try disableCmdTab() -- 这里替换为你的实际按键填充逻辑 repeat 5 times -- 示例:模拟重复填充操作 my ActiveError() -- 确保InDesign始终在前台 keystroke "sample_text" delay 0.5 end repeat on error errMsg display dialog "脚本执行出错:" & errMsg finally -- 无论成功或失败,强制恢复快捷键 restoreCmdTab(originalShortcut) end try
方法2:实时拦截Command+Tab按键
通过System Events持续监听按键事件,一旦检测到Command+Tab组合键就取消输入并切回InDesign。这种方法更直接,但需要持续运行监听循环,资源占用略高。
核心监听代码片段
global scriptRunning -- 启动按键监听循环 on startKeyListener() tell application "System Events" repeat while scriptRunning if (key down command) and (key down tab) then key up tab key up command my ActiveError() -- 立即切回InDesign end if delay 0.05 -- 降低监听频率减少资源消耗 end repeat end tell end startKeyListener -- 主脚本中启动监听(需配合后台执行逻辑) set scriptRunning to true my startKeyListener() -- 执行你的按键填充逻辑后,设置scriptRunning为false停止监听
关键注意事项
- 权限要求:运行脚本的应用(如Script Editor)必须在「系统设置 > 隐私与安全性 > 辅助功能」中获得授权,否则无法修改快捷键或监听按键。
- 异常处理:必须用
try...finally确保快捷键能恢复,避免脚本崩溃后Command+Tab永久失效。 - 系统兼容性:该方案适用于macOS Ventura及以上版本,旧系统可能需要调整快捷键的键名参数。
内容的提问来源于stack exchange,提问作者Ashwin Gopal
相关产品推荐
相关产品推荐

