You need to enable JavaScript to run this app. Kotlin Native使用AXUIElement获取应用窗口的代码转写问题
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 16:45:01