1 module hunt.system.WindowsHelper;
2 
3 // dfmt off
4 version (Windows):
5 // dfmt on
6 
7 import std.exception;
8 import std.stdio;
9 import std.windows.charset;
10 
11 import core.sys.windows.wincon;
12 import core.sys.windows.winbase;
13 import core.sys.windows.windef;
14 import core.stdc.stdio;
15 
16 struct ConsoleHelper {
17     private __gshared HANDLE g_hout;
18     enum defaultColor = FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE;
19 
20     shared static this() {
21         g_hout = GetStdHandle(STD_OUTPUT_HANDLE);
22         resetColor();
23     }
24 
25     static HANDLE getHandle() nothrow {
26         return g_hout;
27     }
28 
29     static void resetColor() nothrow {
30         SetConsoleTextAttribute(g_hout, defaultColor);
31     }
32 
33     static void setTextAttribute(ushort attr) nothrow {
34         SetConsoleTextAttribute(g_hout, attr);
35     }
36 
37     static void write(lazy string msg) nothrow {
38         try {
39             printf("%s\n", toMBSz(msg));
40         } catch(Exception ex) {
41             collectException( {
42                 setTextAttribute(FOREGROUND_RED);
43                 writeln(ex); 
44                 setTextAttribute(defaultColor);
45             }());
46         }
47     }
48 
49     static void writeWithAttribute(lazy string msg, ushort attr = defaultColor) nothrow {
50         setTextAttribute(attr);
51         try {
52             printf("%s\n", toMBSz(msg));
53             if ((attr & defaultColor) != defaultColor)
54                 resetColor();
55         } catch(Exception ex) {
56             collectException( {
57                 setTextAttribute(FOREGROUND_RED);
58                 writeln(ex); 
59                 setTextAttribute(defaultColor);
60             }());
61         }
62     }
63 }
64