Kotlin Native使用AXUIElement获取应用窗口的代码转写问题
Kotlin Native 实现macOS应用窗口属性获取
类型映射说明
Swift 与 Kotlin Native 的 AXUI 系列类型对应关系如下:
- Swift
AXUIElement等价于 Kotlin Native 中的AXUIElementRef类型,属于C指针包装类 - Swift 中
AXUIElementCopyAttributeValue的inout入参,在Kotlin Native中需要用memScoped作用域下alloc申请的CFTypeRefVar?指针接收返回值
完整实现代码
需要先导入依赖包:
import kotlinx.cinterop.* import platform.AppKit.* import platform.CoreFoundation.* import platform.CoreGraphics.*
业务逻辑实现:
fun main() = memScoped { NSWorkspace.sharedWorkspace.runningApplications .filterIsInstance<NSRunningApplication>() .filter { it.active } .forEach { app -> val pid = app.processIdentifier val appRef = AXUIElementCreateApplication(pid) // 获取窗口列表 val windowListPtr = alloc<CFTypeRefVar?>() val getWindowStatus = AXUIElementCopyAttributeValue( element = appRef, attribute = kAXWindowsAttribute as CFString, value = windowListPtr.ptr ) if (getWindowStatus != AXError.kAXErrorSuccess) return@forEach val windowList = windowListPtr.value as? NSArray ?: return@forEach val firstWindow = windowList.firstObject as? AXUIElementRef ?: return@forEach // 获取文档路径 val docPtr = alloc<CFTypeRefVar?>() val getDocStatus = AXUIElementCopyAttributeValue( element = firstWindow, attribute = kAXDocumentAttribute as CFString, value = docPtr.ptr ) if (getDocStatus != AXError.kAXErrorSuccess) return@forEach val docPath = CFBridgingRelease(docPtr.value) as? String ?: return@forEach println("找到文档路径: $docPath") } }
注意事项
- 运行代码需要先在macOS「系统设置→隐私与安全性→辅助功能」中给当前应用授予权限,否则
AXUIElementCopyAttributeValue会返回权限错误 - 类型转换建议使用安全转换
as?避免空指针崩溃,生产环境可补充错误码分支处理,适配权限不足、属性不存在等场景 - CoreFoundation类型返回值需注意内存管理,使用
CFBridgingRelease将CoreFoundation类型桥接为Foundation类型即可自动管理内存
内容的提问来源于stack exchange,提问作者lanyuanxiaoyao
相关产品推荐
相关产品推荐

