How to work Get & Set text in clipboard in Windows ?

Dennis dkorpel at gmail.com
Sat Jun 20 13:46:05 UTC 2020


On Saturday, 20 June 2020 at 13:32:22 UTC, Vinod K Chandran wrote:
> I would like to know how to get & set text in clipboard. I am 
> using windows machine.

This is an example of setting the clipboard using the Windows API 
in D:
```
/// Returns: true on success
bool setClipboard(string str) {
	import core.stdc.string: memcpy;
	import std.string: toStringz;
	import core.sys.windows.windows: GlobalAlloc, GlobalLock, 
GlobalUnlock,
		OpenClipboard, EmptyClipboard, SetClipboardData, CloseClipboard,
		CF_TEXT, CF_UNICODETEXT, GMEM_MOVEABLE;
		
	auto hMem = GlobalAlloc(GMEM_MOVEABLE, str.length + 1);
	if (hMem is null) {
		return false;
	}
	memcpy(GlobalLock(hMem), str.ptr, str.length);
	(cast(char*) hMem)[str.length] = '\0'; // zero terminator
	GlobalUnlock(hMem);
	if (!OpenClipboard(null)) {
		return false;
	}
	EmptyClipboard();
	if (!SetClipboardData(CF_TEXT, hMem)) {
		return false;
	}
	CloseClipboard();
	return true;
}
```

Here's an example of getting it, from arsd:
https://github.com/adamdruppe/arsd/blob/ae17d5a497de93454f58421cd9d4a5ecd70594c0/terminal.d#L2043

Here is a C example from GLFW:
https://github.com/glfw/glfw/blob/51a465ee2b50234f984efce0e229f7e9afceda9a/src/win32_window.c#L2150


More information about the Digitalmars-d-learn mailing list