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

Ale*_*ban 2 clipboard kotlin kotlin-native

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

aFile.txt看起来像这样:

one
two
three
...
...
the last line
Run Code Online (Sandbox Code Playgroud)

到目前为止我的代码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)
    }

}
Run Code Online (Sandbox Code Playgroud)


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

非常感谢。


更新:

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

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

system("echo ${nextLine} | clip")
print("${nextLine}")
Run Code Online (Sandbox Code Playgroud)

2sl*_*oth 6

请尝试以下操作:

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)
}
Run Code Online (Sandbox Code Playgroud)