当应用程序开始关注Mac时,触发一个Apple脚本/自动化器

时间:2020-10-22 06:31:23

标签: macos applescript automator

我想根据应用程序自动进行键盘布局。我正在远程使用Windows VM,因此无法创建可以执行以下操作的脚本:

  1. 在应用程序切换到Windows VM时更改键盘布局
  2. 将其与所有其他应用更改回正常布局。

我很难找到有关应用程序焦点更改的触发事件。是否可以通过自动执行此操作?

否则,请提出其他解决方案以解决该问题。

1 个答案:

答案 0 :(得分:0)

假设您只有两个键盘布局,则可以使用以下脚本应用程序。

首先,您需要打开“系统偏好设置”,然后查看“键盘”➔“快捷方式”➔“输入源”;查看“选择先前的输入源”的键盘快捷键是什么,确保已单击它,然后将其复制到标记位置的脚本中。我将我的设置为comd-ctrl-space(^⌘),但是您的可能有所不同。您还应该检查“ Windows VM”是否是该应用程序的正确名称:在Finder中找到该应用程序,选择它,然后键入⌘I打开“获取信息”窗口,然后在“名称和扩展名”文本框中查找。

现在执行以下操作

  1. 在脚本编辑器中复制以下脚本
  2. 将其另存为打开的应用程序
    • 从左下方的“格式”菜单中选择“应用程序”
    • 点击“运行处理程序后保持打开状态”复选框
  3. 打开系统偏好设置并执行以下操作
    • 将该应用添加到“安全性和隐私”➔“隐私”中的“辅助功能”部分(以便它可以发送键盘快捷键)
    • 将该应用添加到“用户和组”中您帐户的“登录项”部分(这样它会在登录时自动启动)

然后可以运行它并进行测试。该应用程序在后台等待,以接收有关某个应用程序已激活或已停用的通知,然后它会检查该应用程序名称,并在Window VM应用程序出现或消失时触发用于切换输入源的键盘快捷键。

use AppleScript version "2.4"
use framework "AppKit"
use scripting additions

property NSWorkspace : class "NSWorkspace"

on run
    set workSp to NSWorkspace's sharedWorkspace()
    set notifCent to workSp's notificationCenter()
    tell notifCent to addObserver:me selector:"appHasActivated:" |name|:"NSWorkspaceDidActivateApplicationNotification" object:(missing value)
    tell notifCent to addObserver:me selector:"appHasDeactivated:" |name|:"NSWorkspaceDidDeactivateApplicationNotification" object:(missing value)
end run

on idle
    -- we don't use the idle loop, so tell the system to check in once an hour
    return 3600
end idle

on appHasActivated:notif
    set targetApp to (notif's userInfo's valueForKey:"NSWorkspaceApplicationKey")
    set targetAppName to (targetApp's localizedName) as text
    if targetAppName is "Windows VM" then
        tell application "System Events"
            tell process "Windows VM"
                -- change this line to match your 'Select previous input source' keyboard shortcut
                keystroke space using {command down, control down}
            end tell
        end tell
    end if
end appHasActivated:

on appHasDeactivated:notif
    set targetApp to (notif's userInfo's valueForKey:"NSWorkspaceApplicationKey")
    set targetAppName to (targetApp's localizedName) as text
    if targetAppName is "Windows VM" then
        tell application "System Events"
            tell process targetAppName
                -- change this line to match your 'Select previous input source' keyboard shortcut
                keystroke space using {command down, control down}
            end tell
        end tell
    end if
end appHasDeactivated:

一旦您满意,它可以在终端中运行以下命令:

defaults write '/path/to/$name.app/Contents/Info.plist' LSUIElement -bool yes

这会将应用程序变成后台代理,该代理永远不会占据前台,并且在扩展坞中不可见。这样,您就可以忘记它。

相关问题