Go语言学习: clipboard/剪贴板/pbcopy/copy 包

读写系统剪贴板的包 clipboard
更新于: 2024-11-09 23:05:58

安装

go get golang.design/x/clipboard

main.go

  • Write
  • Read
package main

import (
	"fmt"

	"golang.design/x/clipboard"
)

func main() {
	clipboard.Write(clipboard.FmtText, []byte("text data123123xyz"))
	res := clipboard.Read(clipboard.FmtText)
	fmt.Println(string(res))
}

FmtText

复制/写入 文本,这个功能基本正常

FmtImage

测试下来,只能复制截图类型的 image 内容。

如果是以系统文件方式存在的 image,则无法复制

另一个库

源码 https://github.com/skanehira/clipboard-image

测试结论:看起来可以复制图片,但实际图片只是一张固定的图,并不是真实的图片

go get github.com/skanehira/clipboard-image/v2

各种情况的图像

情况示例图片PID
QQ截图
da432263ly1hvg4blo7maj207i078glo
复制文件
da432263ly1hvg4btshowj20sg0sg75f

其它生态解决方案

JS 里,别人用 c++ 的思路解决问题了


利用 oscript 读取单个文件路径

go get -u github.com/afeiship/go-clipfile
package main

import (
	"bytes"
	"fmt"
	"os/exec"
)

func main() {
	// Step 1: Use osascript to get the POSIX path of the file in the clipboard
	cmd := exec.Command("osascript", "-e", `tell application "System Events" to set filePath to (the clipboard as «class furl») as alias`, "-e", `POSIX path of filePath`)

	// Capture the output of the command
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		fmt.Println("Error getting file path from clipboard:", err)
		return
	}

	// Trim any newline or whitespace from the path
	filePath := out.String()
	filePath = filePath[:len(filePath)-1] // Remove trailing newline character

	// Step 2: Open and read the file
	fmt.Println("Opening file:", filePath)
}