Can't change CHAR_INFO Attributes of box drawing characters with an IF() statements

54 Views Asked by At

I was playing around with Windows API console functions for a project that involves drawing an ASCII map. I got everything working the way I want it to until I got to fiddling with foreground and background colors.

I put together the following code to test some things out:

#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <tchar.h>

HANDLE wHnd;

int main(void) {
    wHnd = GetStdHandle(STD_OUTPUT_HANDLE);

    COORD characterBufferSize = { 5,1 };
    COORD characterPosition = { 0,0 };
    SMALL_RECT consoleWriteArea = { 0,0,4,0 };

    CHAR_INFO consoleBuffer[5 * 1];

    int i;

    consoleBuffer[0].Char.AsciiChar = 0x20;   //space
    consoleBuffer[0].Attributes = FOREGROUND_BLUE;
    consoleBuffer[1].Char.AsciiChar = 16;     //left arrow
    consoleBuffer[1].Attributes = FOREGROUND_BLUE;
    consoleBuffer[2].Char.AsciiChar = 0xC9;   //box drawing double lines
    consoleBuffer[2].Attributes = FOREGROUND_BLUE;
    consoleBuffer[3].Char.AsciiChar = 0x1E;   //up arrow
    consoleBuffer[3].Attributes = FOREGROUND_BLUE;
    consoleBuffer[4].Char.AsciiChar = 218;    //box drawing single line
    consoleBuffer[4].Attributes = FOREGROUND_BLUE;

    for (i = 0; i < 5; i++) {
        if (consoleBuffer[i].Char.AsciiChar == 0x20 || consoleBuffer[i].Char.AsciiChar == 16) {
            consoleBuffer[i].Attributes = BACKGROUND_GREEN;
        }
        else if (consoleBuffer[i].Char.AsciiChar == 0xC9 || consoleBuffer[i].Char.AsciiChar == 0x1E) {
            consoleBuffer[i].Attributes = BACKGROUND_GREEN | BACKGROUND_BLUE;
        }
        else if (consoleBuffer[i].Char.AsciiChar == 218) {
            consoleBuffer[i].Attributes = BACKGROUND_RED | BACKGROUND_BLUE;
        }
        else {
            consoleBuffer[i].Attributes = BACKGROUND_RED;
        }
    }

    WriteConsoleOutputA(wHnd, consoleBuffer, characterBufferSize, characterPosition, &consoleWriteArea);

    getchar();
}

The output of this is:

enter image description here

I can set the Attributes for the box drawing characters based on their position in the consoleBuffer array (see foreground colors), but unlike the space and arrow characters, the if(equal) statements fail to target them, and they take on the Attributes under the else() statement instead. This is true whether I use decimal values or hex values.

Does anyone know what causes this behavior and how I could fix it?

0

There are 0 best solutions below