4

For the following questions, answers may be for C/C++, C#, or Python. I would like the answers to be cross platform if possible but I realize I will probably need conio or ncurses

  1. How do I output colored text?
  2. How would I do a GUI like top or nethack where certain things are "drawn" to certain spaces in the terminal?

If possible a small oneliner code example would be great.

4

5 回答 5

4

Yes, these are VT100 escape codes. The simplest thing is to use some flavor of Curses. Once, you choose a curses flavor it is pretty simple to do both 1 and 2.

Here's a HowTo on ncurses.

http://web.cs.mun.ca/~rod/ncurses/ncurses.html

于 2009-02-26T00:54:26.757 回答
1

Most terminal windows understand the ANSI escape sequences, which allow coloring, cursor movement etc. You can find a list of them here.

Use of these sequences can seem a bit "old school", but you can use them in cases where curses isn't really applicable. For example, I use the folowing function in my bash scripts to display error messages in red:

color_red()
{
    echo -e "\033[01;31m$1\033[00m"
}

You can then say things like:

color_red "something has gone horribly wrong!"
exit 1
于 2009-02-26T00:53:24.217 回答
1

从这个角度来看,控制台在许多方面只是对经典终端设备的模拟。Curses 最初是为了支持在不同终端类型上执行通用操作的方式而创建的,其中用户可以选择实际使用的终端作为登录序列的一部分。这种遗产今天在 ncurses 中仍然存在。

ncurses 库提供调用函数以直接定位光标并发出文本,并且已知它适用于 Windows 控制台(运行 CMD.EXE 的地方),以及各种 *nix 平台等价物,例如 XTerms 等。如果你有这样的东西,它甚至可能通过串行线路与真正的 Dec VT100 一起工作......

VT100 及更高型号所理解的转义序列成为 ANSI 标准终端的基础。但你真的不想知道这一点。使用ncurses,你就不必了。

依靠 conio 不会让你跨平台,因为那是一个 DOS/Windows 特定的 API。

编辑:显然ncurses库本身并不容易建立在 mingw 上,至少从快速尝试谷歌搜索中可以看出。然而,一切都没有丢失,因为 ncurses 只是原始curses库的后代之一。

另一个是PDCurses 它可以为 Windows 控制台以及 X11 和各种 *nix 平台编译和运行。

(我刚刚在 Wikipedia 上追逐参考资料时提醒我,curses 来自于编写游戏 rogue,它是 nethack 的祖先。它的一些代码也是从 vi 编辑器的光标管理模块“借来的”。所以探索在nethack 源工具包中的想法可能根本不是一个疯狂的想法......)

于 2009-02-26T00:56:19.780 回答
0

Not cross platform but for Windows / C# colour, see

Color your Console text (C#)

c++

于 2009-02-26T00:55:32.213 回答
0

在 C# 中,您可以分别通过 Console.ForegroundColor 和 Console.BackgroundColor 属性设置文本颜色和背景颜色。有关有效颜色的列表,请参阅此MSDN 文档

于 2009-02-26T00:57:00.340 回答