// Copyright 2013 @atotto. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package clipboard import ( "errors" "syscall" "unsafe" "github.com/lxn/win" ) func readAll() (string, error) { if !win.OpenClipboard(0) { return "", errors.New("OpenClipboard") } defer win.CloseClipboard() hMem := win.HGLOBAL(win.GetClipboardData(win.CF_UNICODETEXT)) if hMem == 0 { return "", errors.New("GetClipboardData") } p := win.GlobalLock(hMem) if p == nil { return "", errors.New("GlobalLock()") } defer win.GlobalUnlock(hMem) text := win.UTF16PtrToString((*uint16)(p)) return text, nil } func writeAll(text string) error { if !win.OpenClipboard(0) { return errors.New("OpenClipboard") } defer win.CloseClipboard() utf16, err := syscall.UTF16FromString(text) if err != nil { return err } hMem := win.GlobalAlloc(win.GMEM_MOVEABLE, uintptr(len(utf16)*2)) if hMem == 0 { return errors.New("GlobalAlloc") } p := win.GlobalLock(hMem) if p == nil { return errors.New("GlobalLock()") } win.MoveMemory(p, unsafe.Pointer(&utf16[0]), uintptr(len(utf16)*2)) win.GlobalUnlock(hMem) if 0 == win.SetClipboardData(win.CF_UNICODETEXT, win.HANDLE(hMem)) { // We need to free hMem. defer win.GlobalFree(hMem) return errors.New("SetClipboardData") } // The system now owns the memory referred to by hMem. return nil }