基本概念相对简单,但实现上有些怪异。以下脚本可满足(A)中的需求,但需要注意它无法区分应用程序被
如何打开。每当应用程序变为活动状态(通过cmd-tab、点击Dock图标、双击应用程序图标等)时,它将运行,并在没有打开窗口或出现其他错误情况时静默失败。
将以下脚本复制到脚本编辑器中,并将其保存为“保持打开”应用程序(从文件格式下拉菜单中选择“应用程序”,并勾选“运行处理程序后保持打开”复选框)。您需要在安全性偏好设置中授予其辅助功能权限,并且每次编辑脚本应用程序时都需要切换这些权限的状态。
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:"activeAppHasChanged:" |name|:"NSWorkspaceDidActivateApplicationNotification" object:(missing value)
end run
on idle
-- we don't use the idle loop, so tell the system let the app sleep. this comes out of idle once an hour
return 3600
end idle
on activeAppHasChanged:notif
set targetApp to (notif's userInfo's valueForKey:"NSWorkspaceApplicationKey")
set targetAppName to (targetApp's localizedName) as text
tell application "System Events"
tell process targetAppName
try
set {xpos, ypos} to position of first window
set {w, h} to size of first window
my mouseMove(xpos + w / 2, ypos + h / 2)
end try
end tell
end tell
end activeAppHasChanged:
on mouseMove(newX, newY)
do shell script "
/usr/bin/python <<END
from Quartz.CoreGraphics import CGEventCreateMouseEvent
from Quartz.CoreGraphics import CGEventPost
from Quartz.CoreGraphics import kCGMouseButtonLeft
from Quartz.CoreGraphics import kCGHIDEventTap
from Quartz.CoreGraphics import kCGEventMouseMoved
import time
def mouseEvent(posx, posy):
theEvent = CGEventCreateMouseEvent(None, kCGEventMouseMoved, (posx,posy), kCGMouseButtonLeft)
CGEventPost(kCGHIDEventTap, theEvent)
mouseEvent(" & newX & "," & newY & ");
END"
end mouseMove
运行脚本并让它在后台运行。每次您切换应用程序时,它都会将光标居中在该应用程序的第一个打开的窗口中。如果您更喜欢选项(B)-使用键盘快捷键的方法也可以实现,但这是一种稍微不同的方法。如果需要帮助实施,请提出要求。