我想使用golang語言制作Mac桌面的屏幕截圖。有一個很好和簡單的工具:https://github.com/kbinani/screenshot 我已經(jīng)使用它很長一段時間了,但最近我試圖再次使用它,并注意到我的兩臺Macbook(big sur和catalina)上有一個奇怪的bahaviour。下面是一個簡單的代碼:package mainimport ( "fmt" "github.com/kbinani/screenshot" "image/png" "os")func main(){ bounds := screenshot.GetDisplayBounds(0) img, err := screenshot.CaptureRect(bounds) if err != nil { panic(err) } fileName := fmt.Sprintf("%d_%dx%d.png", 0, bounds.Dx(), bounds.Dy()) file, _ := os.Create(fileName) defer file.Close() png.Encode(file, img) fmt.Printf("#%d : %v \"%s\"\n", 0, bounds, fileName)}上面的代碼應(yīng)該捕獲第一個屏幕,并將文件像“0_2560x1440.png”一樣保存在二進制附近。當(dāng)我從Jetbrains Goland IDE運行二進制文件時,或者當(dāng)我在Jetbrains Goland IDE終端中使用go run main.go命令時,一切都很好。但是,如果我從默認終端(或iTerm)運行二進制文件或運行main.go,我將收到?jīng)]有任何窗口的屏幕截圖,只是一個沒有任何winodws或foldres的普通桌面。這是什么原因呢?從 IDE 終端或操作系統(tǒng)終端運行二進制文件有什么區(qū)別?經(jīng)過一些考慮,我認為也許在golang屏幕截圖庫中的某個地方有一個錯誤。我試圖使用OSX api運行另一個代碼:package main// To use the two libraries we need to define the respective flags, include the required header files and import "C" immediately afterimport ( // #cgo LDFLAGS: -framework CoreGraphics // #cgo LDFLAGS: -framework CoreFoundation // #include <CoreGraphics/CoreGraphics.h> // #include <CoreFoundation/CoreFoundation.h> "C" "image" "image/png" "os" "reflect" "unsafe" // other packages...)func main() { displayID := C.CGMainDisplayID() width := int(C.CGDisplayPixelsWide(displayID)) height := int(C.CGDisplayPixelsHigh(displayID)) rawData := C.CGDataProviderCopyData(C.CGImageGetDataProvider(C.CGDisplayCreateImage(displayID))) length := int(C.CFDataGetLength(rawData)) ptr := unsafe.Pointer(C.CFDataGetBytePtr(rawData))代碼給出相同的結(jié)果。在 IDE 終端中運行 - 正常行為。在其他地方運行 - 屏幕截圖現(xiàn)在有內(nèi)容。請幫我揭開它的神秘面紗。
1 回答

當(dāng)年話下
TA貢獻1890條經(jīng)驗 獲得超9個贊
經(jīng)過一些調(diào)查,發(fā)現(xiàn)問題只是OSX權(quán)限。有屏幕錄制權(quán)限。IDE允許這樣做,但不適用于終端。
沒有彈出窗口或類似的東西。
- 1 回答
- 0 關(guān)注
- 84 瀏覽
添加回答
舉報
0/150
提交
取消