github.com/gop9/olt@v0.0.0-20200202132135-d956aad50b08/framework/clipboard/clipboard_windows.go (about) 1 // Copyright 2013 @atotto. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package clipboard 6 7 import ( 8 "fmt" 9 "os" 10 "syscall" 11 "unsafe" 12 ) 13 14 const ( 15 cfUnicodetext = 13 16 gmemFixed = 0x0000 17 ) 18 19 var ( 20 user32 = syscall.MustLoadDLL("user32") 21 openClipboard = user32.MustFindProc("OpenClipboard") 22 closeClipboard = user32.MustFindProc("CloseClipboard") 23 emptyClipboard = user32.MustFindProc("EmptyClipboard") 24 getClipboardData = user32.MustFindProc("GetClipboardData") 25 setClipboardData = user32.MustFindProc("SetClipboardData") 26 27 kernel32 = syscall.NewLazyDLL("kernel32") 28 globalAlloc = kernel32.NewProc("GlobalAlloc") 29 globalFree = kernel32.NewProc("GlobalFree") 30 globalLock = kernel32.NewProc("GlobalLock") 31 globalUnlock = kernel32.NewProc("GlobalUnlock") 32 lstrcpy = kernel32.NewProc("lstrcpyW") 33 ) 34 35 func readAll() (string, error) { 36 r, _, err := openClipboard.Call(0) 37 if r == 0 { 38 return "", err 39 } 40 defer closeClipboard.Call() 41 42 h, _, err := getClipboardData.Call(cfUnicodetext) 43 if r == 0 { 44 return "", err 45 } 46 47 l, _, err := globalLock.Call(h) 48 if l == 0 { 49 return "", err 50 } 51 52 text := syscall.UTF16ToString((*[1 << 20]uint16)(unsafe.Pointer(l))[:]) 53 54 r, _, err = globalUnlock.Call(h) 55 if r == 0 { 56 return "", err 57 } 58 59 return text, nil 60 } 61 62 func writeAll(text string) error { 63 r, _, err := openClipboard.Call(0) 64 if r == 0 { 65 return err 66 } 67 defer closeClipboard.Call() 68 69 r, _, err = emptyClipboard.Call(0) 70 if r == 0 { 71 return err 72 } 73 74 data := syscall.StringToUTF16(text) 75 76 h, _, err := globalAlloc.Call(gmemFixed, uintptr(len(data)*int(unsafe.Sizeof(data[0])))) 77 if h == 0 { 78 return err 79 } 80 81 l, _, err := globalLock.Call(h) 82 if l == 0 { 83 return err 84 } 85 86 r, _, err = lstrcpy.Call(l, uintptr(unsafe.Pointer(&data[0]))) 87 if r == 0 { 88 return err 89 } 90 91 r, _, err = globalUnlock.Call(h) 92 if r == 0 { 93 return err 94 } 95 96 r, _, err = setClipboardData.Call(cfUnicodetext, h) 97 if r == 0 { 98 return err 99 } 100 return nil 101 } 102 103 func Start() { 104 } 105 106 func Get() string { 107 str, err := readAll() 108 if err != nil { 109 fmt.Fprintln(os.Stderr, err) 110 return "" 111 } 112 return str 113 } 114 115 func GetPrimary() string { 116 return "" 117 } 118 119 func Set(text string) { 120 err := writeAll(text) 121 if err != nil { 122 fmt.Fprintln(os.Stderr, err) 123 } 124 }