2012-02-08 9 views
12

私は "textcolor();"を知っています。 C++のためのもので、私はunixのためのメソッドを見てきました... しかし、Windowsのための方法もありますか?ウィンドウ内のターミナルアプリケーションのCカラーテキスト

#include <stdio.h> 
int main() 
{ 
    printf("\ntest - C programming text color!"); 
    printf("\n--------------------------------"); 
    printf("\n\n\t\t-BREAK-\n\n"); 
    textcolor(15); 
    printf("WHITE\n"); 
    textcolor(0); 
    printf("BLACK\n"); 
    textcolor(4); 
    printf("RED\n"); 
    textcolor(1); 
    printf("BLUE\n"); 
    textcolor(2); 
    printf("GREEN\n"); 
    textcolor(5); 
    printf("MAGENTA\n"); 
    textcolor(14); 
    printf("YELLOW\n"); 
    textcolor(3); 
    printf("CYAN\n"); 
    textcolor(7); 
    printf("LIGHT GRAY\n"); 
} 

私は、ネット上の任意の何かを見つけることができません... はのは、スタックオーバーフローから良い人々が役立つことを願ってみましょう。ここではD

Cしてくださいではなく、C++

答えて

28

あなたがそうCとWindowsの特定をしたいので、私は、Win32 APIでSetConsoleTextAttribute()関数を使うことをお勧めします。コンソールへのハンドルを取得し、適切な属性を渡す必要があります。簡単な例として

/* Change console text color, then restore it back to normal. */ 
#include <stdio.h> 
#include <windows.h> 

int main() { 
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); 
    CONSOLE_SCREEN_BUFFER_INFO consoleInfo; 
    WORD saved_attributes; 

    /* Save current attributes */ 
    GetConsoleScreenBufferInfo(hConsole, &consoleInfo); 
    saved_attributes = consoleInfo.wAttributes; 

    SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE); 
    printf("This is some nice COLORFUL text, isn't it?"); 

    /* Restore original attributes */ 
    SetConsoleTextAttribute(hConsole, saved_attributes); 
    printf("Back to normal"); 

    return 0; 
} 

使用可能な属性の詳細情報については、hereを見て。

希望すると便利です。 :)

+0

ありがとう、それは素晴らしい、ちょうどデフォルトのライトグレーに戻すように設定することを迷惑?どうもありがとう! –

+0

@JoeDFこれを行うには、元の属性を 'GetConsoleScreenBufferInfo()'で読み込み、それらを変数に格納し、完了したら復元する必要があります。私はこれを行う方法を示す答えを更新しました。 :) – Miguel

+0

ありがとうございます! :D –

-3

"include windows.h"を使用する2番目の方法が動作します。もう1つはたぶん始まりです

+0

私はこれがミゲルの答えに対する反応だと思いますか?あなたはそのためにコメントを使うべきです。代わりに新しい回答を追加しました。 –

関連する問題