package main import ( "fmt" "syscall" "unsafe" "github.com/tadvi/winc/w32" ) // setClipboardText puts s on the Windows clipboard as CF_UNICODETEXT so it // can be pasted with Ctrl+V. After SetClipboardData succeeds the memory is // owned by the clipboard, so it must not be freed here. func setClipboardText(s string) error { if !w32.OpenClipboard(0) { return fmt.Errorf("OpenClipboard failed") } defer w32.CloseClipboard() if !w32.EmptyClipboard() { return fmt.Errorf("EmptyClipboard failed") } u16, err := syscall.UTF16FromString(s) // includes the terminating NUL if err != nil { return fmt.Errorf("UTF16 conversion: %w", err) } h := w32.GlobalAlloc(w32.GMEM_MOVEABLE, uint32(len(u16)*2)) p := w32.GlobalLock(h) copy(unsafe.Slice((*byte)(p), len(u16)*2), unsafe.Slice((*byte)(unsafe.Pointer(&u16[0])), len(u16)*2)) w32.GlobalUnlock(h) if w32.SetClipboardData(w32.CF_UNICODETEXT, h) == 0 { return fmt.Errorf("SetClipboardData failed") } return nil }