Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print colors into the console with D?

I have tried escape sequences with the writeln() function, I also tried to use them with the printf() function imported from the std.c.stdlib module, but it only prints an empty line.

printf("\0x1B[5;32;40m Blink Text");

printf("\e[5;32;40m Blink Text\e[m");

writeln("\0x1b\x5b1;31;40m\tColor");

None of these work.

I have tried everything I can think of, is there a way?

Searching the D website's library reference didn't help me.


EDIT: SOLUTION

Okay, so I have tried to import the function SetConsoleTextAttribute, as Mars kindly suggested:

extern (Windows) bool SetConsoleTextAttribute(void*, ushort);

I also imported the other function (Which I simply guessed I need to import, as I have no previous experience with Win programming)

extern (Windows) void* GetStdHandle(uint);

And simply called the two functions

auto handle  = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(handle, FOREGROUND_BLUE);
writeln("In Color");

This works perfectly, thank you all so much for your time and help

like image 911
Pavel Matuska Avatar asked Feb 19 '12 16:02

Pavel Matuska


3 Answers

Like CyberShadow pointed out, you have to use \x1B, or \033. It should work fine, as long as you're on Linux. Windows doesn't support those codes though. Here you have to use the API function SetConsoleTextAttribute from std.c.windows.windows.

like image 113
Mars Avatar answered Sep 29 '22 14:09

Mars


There is a typo in your string: use \x1B instead of \0x1B.

D doesn't support the \e escape code in strings, use \x1B.

like image 32
Vladimir Panteleev Avatar answered Sep 29 '22 14:09

Vladimir Panteleev


You may also try a helper module like http://www.digitalmars.com/d/archives/digitalmars/D/Color_your_terminal_s_output_146182.html

like image 23
Trass3r Avatar answered Sep 29 '22 13:09

Trass3r