MacOS Swift获取活跃应用窗口及AXError-25204报错解决
Mac菜单栏应用窗口尺寸调整问题:AXError(-25204) 解决记录
我开发了一款Mac菜单栏应用,期望通过快捷键组合调整当前活跃应用窗口的尺寸。在实现获取当前活跃应用窗口列表的功能时,按下快捷键始终报错:Failed to retrieve windows, error: AXError(rawValue: -25204)。已为应用开启辅助功能权限,且在不同应用上测试均出现该问题(基于macOS 14、Swift 5)。
初始报错代码
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)
沙箱修复后的可运行代码
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)") } print("HERE!!!!!") return } if let firstWindow = windows.first { var newSize = CGSize(width: 800, height: 600) // Desired size var sizeValue: AXValue? sizeValue = AXValueCreate(AXValueType.cgSize, &newSize) if let sizeValue = sizeValue { let setSizeResult = AXUIElementSetAttributeValue(firstWindow, kAXSizeAttribute as CFString, sizeValue) if setSizeResult != .success { print("Failed to resize window, error: \(setSizeResult)") } } else { print("Failed to create AXValue for size.") } } debugPrint(appElement) debugPrint("RESULT is \(result)") } }
内容的提问来源于stack exchange,提问作者cosmicRover
相关产品推荐
相关产品推荐

