[英]Kotlin Native use AXUIElement
我嘗試獲取所有應用程序的窗口。
fun main() = memScoped {
NSWorkspace.sharedWorkspace.runningApplications()
.map { it as NSRunningApplication }
.filter { it.active }
.forEach {
val applicationRef = AXUIElementCreateApplication(it.processIdentifier)
...
}
}
但我無法在 kotlin 本地庫中找到AXUIElement
,但AXUIElementRef
和AXUIElementRefVar
。 許多文章展示了獲取AXUIElement
的 swift 代碼,但我不知道如何將代碼更改為 kotlin。
像這樣的swift代碼:
if let pid = proToolsApp?.processIdentifier {
var result = [AXUIElement]()
var windowList: AnyObject? = nil // [AXUIElement]
let appRef = AXUIElementCreateApplication(pid)
if AXUIElementCopyAttributeValue(appRef, "AXWindows" as CFString, &windowList) == .success {
result = windowList as! [AXUIElement]
}
var docRef: AnyObject? = nil
if AXUIElementCopyAttributeValue(result.first!, "AXDocument" as CFString, &docRef) == .success {
let result = docRef as! AXUIElement
print("Found Document: \(result)")
let filePath = result as! String
print(filePath)
}
}
AXUIElement
只是AXUIElementRef
( https://developer.apple.com/documentation/applicationservices/axuielementref?language=objc ) 的一個快速解釋版本
這在 kotlin 中應該是這樣的:
fun windowTest() = memScoped {
NSWorkspace.sharedWorkspace.runningApplications()
.map { it as NSRunningApplication }
.filter { it.active }
.forEach {
val applicationRef = AXUIElementCreateApplication(it.processIdentifier)!!
val output = alloc<CFTypeRefVar>()
var result = AXUIElementCopyAttributeValue(
applicationRef,
attribute = kAXWindowsAttribute.toCFString(),
value = output.ptr,
)
if (result != kAXErrorSuccess) {
println("error $result")
return@forEach
}
val firstOutput = CFArrayGetValueAtIndex(output.value as CFArrayRef, 0)!!
result = AXUIElementCopyAttributeValue(
element = firstOutput.reinterpret(),
attribute = kAXDocumentAttribute.toCFString(),
value = output.ptr,
)
println("$result ${output.value}")
}
}
fun String.toCFString(): CFStringRef = CFBridgingRetain(this)!!.reinterpret()
在我的情況下,第二個AXUIElementCopyAttributeValue
返回-25212 = kAXErrorNoValue
,我不確定是什么問題,但我在 swift/kotlin 代碼中得到相同的結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.