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

MacOS多显示器下如何仅切换当前聚焦显示器单空间窗口?

解决Hammerspoon多显示器下仅切换当前聚焦显示器窗口的问题

在MacOS中,默认Cmd+Tab切换窗口会显示所有活跃窗口。我用Hammerspoon实现了仅在单个桌面空间内切换窗口的功能,单显示器环境下运行正常,但连接多显示器后,切换器会包含当前桌面空间下其他显示器的窗口,希望修改为仅显示当前聚焦显示器的窗口。

原正常运行脚本(单显示器)

local wf = hs.window.filter
filter = wf.new():setCurrentSpace(true):setDefaultFilter{}
switcher_space = hs.window.switcher.new(filter)
hs.window.switcher.ui.showThumbnails = false
hs.window.switcher.ui.showSelectedThumbnail = false
hs.hotkey.bind('alt', 'tab', 'Next window', function()
    switcher_space:next()
    hs.alert.closeAll()
end)
hs.hotkey.bind('alt-shift', 'tab', 'Prev window', function()
    switcher_space:previous()
    hs.alert.closeAll()
end)

尝试修改后的错误情况

尝试用setScreens方法限制窗口所属屏幕,编写代码如下:

screen_id = hs.screen.primaryScreen():id()
filter = wf.new():setScreens(screen_id):setCurrentSpace(true):setDefaultFilter{}

运行时抛出错误:

invalid key in filter table: _allowedScreens

正确解决方案

问题出在setScreens的参数类型错误,它不接受屏幕ID,而是需要传入屏幕对象。此外,不能固定使用主屏幕,要动态获取当前用户聚焦的屏幕。修正后的完整脚本如下:

local wf = hs.window.filter
local switcher_space

-- 动态生成当前聚焦屏幕的窗口过滤器
local function getCurrentScreenFilter()
    local current_screen = hs.screen.mainScreen() -- 获取当前有焦点的屏幕
    return wf.new():setCurrentSpace(true):setScreens(current_screen):setDefaultFilter{}
end

-- 初始化窗口切换器
switcher_space = hs.window.switcher.new(getCurrentScreenFilter())
hs.window.switcher.ui.showThumbnails = false
hs.window.switcher.ui.showSelectedThumbnail = false

-- 绑定切换快捷键,每次触发时更新过滤器
hs.hotkey.bind('alt', 'tab', 'Next window', function()
    switcher_space:setFilter(getCurrentScreenFilter())
    switcher_space:next()
    hs.alert.closeAll()
end)

hs.hotkey.bind('alt-shift', 'tab', 'Prev window', function()
    switcher_space:setFilter(getCurrentScreenFilter())
    switcher_space:previous()
    hs.alert.closeAll()
end)

关键说明

  • hs.screen.mainScreen()会返回当前用户正在操作的聚焦屏幕,而非固定的主显示器,适配多显示器切换场景
  • 每次触发切换快捷键时更新过滤器,确保始终只筛选当前聚焦屏幕+当前桌面空间内的窗口
  • setScreens方法接受屏幕对象或屏幕对象数组,避免了传入ID导致的参数错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 08:16:05