1 module clipboard_windows;
2 
3 version(Windows) {
4 	import std.stdio;
5 	import core.stdc..string;
6 	import core.stdc.wchar_;
7 	import core.sys.windows.windows;
8 	import std..string;
9 	import std.conv;
10 	import std.utf;
11 
12 	extern(Windows) {
13 		bool OpenClipboard(void*);
14 		void* GetClipboardData(uint);
15 		void* SetClipboardData(uint, void*);
16 		bool EmptyClipboard();
17 		bool CloseClipboard();
18 		void* GlobalAlloc(uint, size_t);
19 		void* GlobalLock(void*);
20 		bool GlobalUnlock(void*);
21 		bool SetConsoleCP(uint);
22 		bool SetConsoleOutputCP(uint);
23 	}
24 
25 	/**
26 		Read a string from the clipboard.
27 	*/
28 	public wstring readClipboard() {
29 		if (OpenClipboard(null)) {
30 			scope(exit) {
31 				CloseClipboard();
32 			}
33 			auto cstr = cast(wchar*)GetClipboardData(13);
34 			if(cstr) {
35 				return to!wstring(cstr[0..wcslen(cstr)]);
36 			} else {
37 				return ""w;
38 			}
39 		} else {
40 			return ""w;
41 		}
42 	}
43 
44 	/**
45 		Write a string to the clipboard.
46 	*/
47 	public void writeClipboard(wstring text) {
48 		if (OpenClipboard(null)) {
49 			scope(exit) {
50 				CloseClipboard();
51 			}
52 			
53 			auto data = toUTF16z(text);
54 			void* handle = GlobalAlloc(0, (to!wstring(text).length + 1) * 2); // each wchar needs two bytes!
55 			void* ptr = GlobalLock(handle);
56 			
57 			memcpy(ptr, data, (to!wstring(text).length + 1) * 2); // each wchar needs two bytes!
58 			GlobalUnlock(handle);
59 			SetClipboardData(13, handle);
60 		}
61 	}
62 
63 	/**
64 		Clears the clipboard.
65 	*/
66 	public void clearClipboard() {
67 		EmptyClipboard();
68 	}
69 
70 	/**
71 		Prepare the console in order to read and write UTF8 strings.
72 	*/
73 	public void prepareConsole() {
74 		SetConsoleCP(65001);
75 		SetConsoleOutputCP(65001);
76 	}
77 }