How can I change the text color in the windows com

2019-01-22 22:01发布

I have a command line program, which outputs logging to the screen.

I want error lines to show up in red. Is there some special character codes I can output to switch the text color to red, then switch it back to white?

I'm using ruby but I imagine this would be the same in any other language.

Something like:

red = "\0123" # character code
white = "\0223"

print "#{red} ERROR: IT BROKE #{white}"
print "other stuff"

14条回答
戒情不戒烟
2楼-- · 2019-01-22 22:06

on ANSI escape codes:

32-bit character-mode (subsystem:console) Windows applications don't write ANSI escape sequences to the console

They must interpret the escape code actions and call the native Console API instead

Thanks microsoft :-(

查看更多
beautiful°
3楼-- · 2019-01-22 22:10
在下西门庆
4楼-- · 2019-01-22 22:17

You could use an ANSI escape sequence, but that won't do what you want under modern versions of Windows. Wikipedia has a very informative article:

http://en.wikipedia.org/wiki/ANSI_escape_code

So the answer to your original question is almost certainly "no." However, you can change the foreground color without writing an escape sequence, for example by invoking a Win32 API function. I don't know how to do this sort of thing in Ruby off the top of my head, but somebody else seems to have managed:

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/241925

I imagine you'd want to use 4 for dark red or 12 for bright red, and 7 to restore the default color.

Hope this helps!

查看更多
迷人小祖宗
5楼-- · 2019-01-22 22:17

I've been using a freeware windows tail program called baretail (google it) for ages that lets you do a windows-appified version of unix tail command. It lets you colorize lines dependent on whatever keywords you define. What's nice about it as a solution is its not tied to a specific language or setup, etc, you just define your color scheme and its on like donkey kong. In my personal top 10 freeware helpers!

查看更多
Juvenile、少年°
6楼-- · 2019-01-22 22:18

As far as I know it is not possible with a command line, it is just one color...

查看更多
我欲成王,谁敢阻挡
7楼-- · 2019-01-22 22:19

A lot of the old ANSI Color Codes work. The code for a red foreground is something like Escape-[31m. Escape is character 27, so that's "\033[31m" or "\x1B[31m", depending on your escaping scheme.

[39m is the code to return to default color.

It's also possible to specify multiple codes at once to set foreground and background color simultaneously.

You may have to load ANSI.sys, see this page.

查看更多
登录 后发表回答