gpt4 book ai didi

kotlin - 如何使用 Kotlin/Native 应用程序将字符串写入剪贴板(Windows 操作系统)?

转载 作者:行者123 更新时间:2023-12-05 08:52:31 24 4
gpt4 key购买 nike

我是 Kotlin 的新手,在 Windows 上使用 Kotlin/Native 制作命令行 .exe。应用程序应从文本文件中读取并逐行打印在屏幕上。当它到达文件的最后一行时,应该将其放入剪贴板。

aFile.txt 看起来像这样:

one
two
three
...
...
the last line

我目前拥有的代码 read.kt (Kotlin/Native) 是这样的:

import kotlinx.cinterop.*
import platform.posix.*

fun main(args: Array<String>) {

if (args.size != 1) {
println("Usage: read.exe <file.txt>")
return
}

val fileName = args[0]
val file = fopen(fileName, "r")

if (file == null) {
perror("cannot open input file $fileName")
return
}

try {
memScoped {
val bufferLength = 64 * 1024
val buffer = allocArray<ByteVar>(bufferLength)

do {
val nextLine = fgets(buffer, bufferLength, file)?.toKString()
if (nextLine == null || nextLine.isEmpty()) break
print("${nextLine}")
} while (true)

}
} finally {
fclose(file)
}

}


上面的代码在屏幕上打印了每一行,但是如何在计算机的剪贴板中写入字符串 "the last line" 呢?如果可能的话,我正在寻找 native (非 Java)解决方案。

非常感谢。


Update:

显然,这不是我正在寻找的解决方案,但我还不明白他们在这里谈论的是什么 (https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-setclipboarddata)。

作为临时修复,我能够使用 system()echoclip 获得我需要的东西,代码如下:

system("echo ${nextLine} | clip")
print("${nextLine}")

最佳答案

尝试以下操作:

import java.awt.Toolkit
import java.awt.datatransfer.Clipboard
import java.awt.datatransfer.StringSelection

fun setClipboard(s: String) {
val selection = StringSelection(s)
val clipboard: Clipboard = Toolkit.getDefaultToolkit().systemClipboard
clipboard.setContents(selection, selection)
}

关于kotlin - 如何使用 Kotlin/Native 应用程序将字符串写入剪贴板(Windows 操作系统)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56643124/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com