2018-08-30 12:36:03 +00:00
|
|
|
// 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 (
|
2018-08-30 14:04:24 +00:00
|
|
|
"errors"
|
2018-08-30 12:36:03 +00:00
|
|
|
"syscall"
|
|
|
|
"unsafe"
|
|
|
|
|
2018-08-30 14:04:24 +00:00
|
|
|
"github.com/lxn/win"
|
2018-08-30 12:36:03 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func readAll() (string, error) {
|
2018-08-30 14:04:24 +00:00
|
|
|
if !win.OpenClipboard(0) {
|
|
|
|
return "", errors.New("OpenClipboard")
|
2018-08-30 12:36:03 +00:00
|
|
|
}
|
2018-08-30 14:04:24 +00:00
|
|
|
defer win.CloseClipboard()
|
|
|
|
hMem := win.HGLOBAL(win.GetClipboardData(win.CF_UNICODETEXT))
|
|
|
|
if hMem == 0 {
|
|
|
|
return "", errors.New("GetClipboardData")
|
2018-08-30 12:36:03 +00:00
|
|
|
}
|
2018-08-30 14:04:24 +00:00
|
|
|
p := win.GlobalLock(hMem)
|
|
|
|
if p == nil {
|
|
|
|
return "", errors.New("GlobalLock()")
|
2018-08-30 12:36:03 +00:00
|
|
|
}
|
2018-08-30 14:04:24 +00:00
|
|
|
defer win.GlobalUnlock(hMem)
|
|
|
|
text := win.UTF16PtrToString((*uint16)(p))
|
2018-08-30 12:36:03 +00:00
|
|
|
return text, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func writeAll(text string) error {
|
2018-08-30 14:04:24 +00:00
|
|
|
if !win.OpenClipboard(0) {
|
|
|
|
return errors.New("OpenClipboard")
|
2018-08-30 12:36:03 +00:00
|
|
|
}
|
2018-08-30 14:04:24 +00:00
|
|
|
defer win.CloseClipboard()
|
|
|
|
utf16, err := syscall.UTF16FromString(text)
|
|
|
|
if err != nil {
|
2018-08-30 12:36:03 +00:00
|
|
|
return err
|
|
|
|
}
|
2018-08-30 14:04:24 +00:00
|
|
|
hMem := win.GlobalAlloc(win.GMEM_MOVEABLE, uintptr(len(utf16)*2))
|
|
|
|
if hMem == 0 {
|
|
|
|
return errors.New("GlobalAlloc")
|
2018-08-30 12:36:03 +00:00
|
|
|
}
|
2018-08-30 14:04:24 +00:00
|
|
|
p := win.GlobalLock(hMem)
|
|
|
|
if p == nil {
|
|
|
|
return errors.New("GlobalLock()")
|
2018-08-30 12:36:03 +00:00
|
|
|
}
|
2018-08-30 14:04:24 +00:00
|
|
|
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")
|
2018-08-30 12:36:03 +00:00
|
|
|
}
|
2018-08-30 14:04:24 +00:00
|
|
|
// The system now owns the memory referred to by hMem.
|
2018-08-30 12:36:03 +00:00
|
|
|
return nil
|
|
|
|
}
|