我正在尝试获取用户当前正在使用的应用程序的活动窗口列表。我的最终目标是能够在某些按钮组合按下时将它们的大小调整到一定的高度/宽度。我的应用程序是菜单栏应用程序。这是我的代码:
import Cocoa
import ApplicationServices
struct WindowManager {
func handleWindowResizeOperation() {
self.getFocusedApp()
}
private func getFocusedApp() {
let options: NSDictionary = [kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true]
let accessEnabled = AXIsProcessTrustedWithOptions(options)
guard accessEnabled else {
print("Accessibility permissions are not enabled.")
return
}
guard let app = NSWorkspace.shared.frontmostApplication else {
print("No frontmost application found.")
return
}
let appElement = AXUIElementCreateApplication(app.processIdentifier)
var value: CFTypeRef?
let result = AXUIElementCopyAttributeValue(appElement, kAXWindowsAttribute as CFString, &value)
guard result == .success, let windows = value as? [AXUIElement], !windows.isEmpty else {
if result == .success {
print("No windows found for the application.")
} else {
print("Failed to retrieve windows, error: \(result)")
}
return
}
debugPrint(appElement)
}
}
每当我按下按钮组合时,我都会得到输出:
Failed to retrieve windows, error: AXError(rawValue: -25204)
我已启用辅助功能权限。请让我知道接下来我需要尝试什么? 我使用的是 MacOS 14,使用的是 swift 5。
我为我的 Mac 应用程序添加了辅助功能权限。我尝试在不同的打开的应用程序上执行按钮组合。我总是得到相同的输出。
错误
-25204
对应kAXErrorCannotComplete
错误代码,通常表示由于应用程序不可访问而无法完成辅助操作。
您可以遵循一些步骤
1- 为您的应用程序启用辅助功能。 ✅
我想你已经做到了。 请检查密钥
NSAppleEventsUsageDescription
以及解释为什么您的应用程序需要控制其他应用程序的字符串值。
2- 启用辅助设备的访问
在 Info.plist 文件中,添加另一行,其中包含键
UISupportsFullScreenInAssistiveAccess
和一个值,解释为什么您的应用程序需要控制其他应用程序。
3-在运行时请求辅助权限
在应用程序的代码中,当应用程序启动或用户尝试执行窗口大小调整操作时请求辅助功能权限。您可以使用
AXIsProcessTrustedWithOptions
函数检查应用程序是否已被授予访问权限,如果没有,则提示用户授予权限。
import Cocoa
import ApplicationServices
func requestAccessibilityPermission() {
let options: NSDictionary = [kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true]
let accessEnabled = AXIsProcessTrustedWithOptions(options)
if !accessEnabled {
DispatchQueue.main.async {
let alert = NSAlert()
alert.messageText = "Grant Accessibility Permission"
alert.informativeText = "This app needs accessibility permissions to resize windows. Please enable accessibility in System Preferences."
alert.addButton(withTitle: "Open System Preferences")
alert.addButton(withTitle: "Cancel")
if alert.runModal() == .alertFirstButtonReturn {
NSWorkspace.shared.openFile(URL(fileURLWithPath: "/System/Library/PreferencePanes/UniversalAccessPref.prefPane"))
}
}
}
}
进行这些更改后,您的应用程序应该能够从最前面的应用程序检索窗口列表并执行调整大小操作。
如果您仍然遇到问题,您可能需要使用有效的开发人员证书签署您的应用程序并启用应用程序沙箱。此外,请确保您的系统的辅助功能权限设置正确,并且您的应用程序已在辅助功能首选项中列出。
PS:认识辅助访问