SetText sets the current text data of the clipboard.
(s string)
| 120 | |
| 121 | // SetText sets the current text data of the clipboard. |
| 122 | func (c *ClipboardService) SetText(s string) error { |
| 123 | return c.withOpenClipboard(func() error { |
| 124 | utf16, err := syscall.UTF16FromString(s) |
| 125 | if err != nil { |
| 126 | return err |
| 127 | } |
| 128 | |
| 129 | hMem := win.GlobalAlloc(win.GMEM_MOVEABLE, uintptr(len(utf16)*2)) |
| 130 | if hMem == 0 { |
| 131 | return lastError("GlobalAlloc") |
| 132 | } |
| 133 | |
| 134 | p := win.GlobalLock(hMem) |
| 135 | if p == nil { |
| 136 | return lastError("GlobalLock()") |
| 137 | } |
| 138 | |
| 139 | win.MoveMemory(p, unsafe.Pointer(&utf16[0]), uintptr(len(utf16)*2)) |
| 140 | |
| 141 | win.GlobalUnlock(hMem) |
| 142 | |
| 143 | if 0 == win.SetClipboardData(win.CF_UNICODETEXT, win.HANDLE(hMem)) { |
| 144 | // We need to free hMem. |
| 145 | defer win.GlobalFree(hMem) |
| 146 | |
| 147 | return lastError("SetClipboardData") |
| 148 | } |
| 149 | |
| 150 | // The system now owns the memory referred to by hMem. |
| 151 | |
| 152 | return nil |
| 153 | }) |
| 154 | } |
| 155 | |
| 156 | func (c *ClipboardService) withOpenClipboard(f func() error) error { |
| 157 | if !win.OpenClipboard(c.hwnd) { |
nothing calls this directly
no test coverage detected