在C中使用printf的彩色文本

Bug*_*tGG 15 c windows printf colors

我想知道如何在控制台中打印出彩色文字?我使用eclipse win64 os.它与编译器有关吗?任何人都可以在C中给出一个简单的例子,只有一个红色或任何颜色的hello世界文本?

nma*_*rko 18

我知道这在C++中非常容易实现,但我发现这可以在C中看到:

#include <stdio.h>
#include <windows.h>   // WinApi header

int main()
{
  HANDLE  hConsole;
    int k;

  hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

  // you can loop k higher to see more color choices
  for(k = 1; k < 255; k++)
  {
    SetConsoleTextAttribute(hConsole, k);
    printf("%3d  %s\n", k, "I want to be nice today!");
  }

  getchar();  // wait
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

所有评论都将帮助您找到完成代码的方式 - 希望它有所帮助!

  • “我知道这在 C++ 中非常容易做到”是什么意思? (3认同)

daj*_*ric 7

您也可以在 Windows 上使用 ANSI 转义序列,并进行以下修改:

reg add HKEY_CURRENT_USER\Console /v VirtualTerminalLevel /t REG_DWORD /d 0x00000001 /f
Run Code Online (Sandbox Code Playgroud)

例子:

int main() 
{
   printf("\033[33mThis is yellow\033[0m");
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

来源: https ://www.codeproject.com/Tips/5255355/How-to-Put-Color-on-Windows-Console


Let*_*_Be 5

如果要在Windows控制台中打印彩色文本,则必须使用Windows API.Windows中不再存在ANSI.sys支持.

在Linux中,您仍然可以使用ANSI转义序列来着色文本.