Swift tapCreate() 禁用后自动启用
Swift tapCreate() auto enable after disabled
我创建了水龙头:
guard let eventTap = CGEvent.tapCreate(tap: .cgSessionEventTap,
place: .headInsertEventTap,
options: .defaultTap,
eventsOfInterest: CGEventMask(eventMask),
callback: myCGEventCallback,
userInfo: nil) else {
logger.info("failed to create event tap")
exit(1)
}
我的应用程序按预期运行。我的应用程序也可能会在 tapCreate()
之后的任何时刻锁定机器,如下所示:
let task = Process()
task.arguments = ["-suspend"]
task.launchPath = "/System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/CGSession"
task.launch()
使用上述代码进入登录屏幕并重新登录后,上面创建的水龙头被关闭 exit。
我一直未能找到登录挂钩或在用户重新登录后重新创建我的 tap
的方法。在这种情况下如何重新启动 tap
?
找到了一种在用户重新登录时获得通知的方法。这仅在启动应用程序的用户重新登录时触发。在 applicationDidFinishLaunching
中,我添加了:
NSWorkspace.shared().notificationCenter.addObserver(self, selector: #selector(self.rebuildEventChains(aNotification:)), name: NSNotification.Name.NSWorkspaceSessionDidBecomeActive, object: nil);
登录时调用的函数:
func rebuildEventChains(aNotification : NSNotification){
// re-enable the tap if is disabled
// ...
}
我创建了水龙头:
guard let eventTap = CGEvent.tapCreate(tap: .cgSessionEventTap,
place: .headInsertEventTap,
options: .defaultTap,
eventsOfInterest: CGEventMask(eventMask),
callback: myCGEventCallback,
userInfo: nil) else {
logger.info("failed to create event tap")
exit(1)
}
我的应用程序按预期运行。我的应用程序也可能会在 tapCreate()
之后的任何时刻锁定机器,如下所示:
let task = Process()
task.arguments = ["-suspend"]
task.launchPath = "/System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/CGSession"
task.launch()
使用上述代码进入登录屏幕并重新登录后,上面创建的水龙头被关闭 exit。
我一直未能找到登录挂钩或在用户重新登录后重新创建我的 tap
的方法。在这种情况下如何重新启动 tap
?
找到了一种在用户重新登录时获得通知的方法。这仅在启动应用程序的用户重新登录时触发。在 applicationDidFinishLaunching
中,我添加了:
NSWorkspace.shared().notificationCenter.addObserver(self, selector: #selector(self.rebuildEventChains(aNotification:)), name: NSNotification.Name.NSWorkspaceSessionDidBecomeActive, object: nil);
登录时调用的函数:
func rebuildEventChains(aNotification : NSNotification){
// re-enable the tap if is disabled
// ...
}