I recently enabled ANSI escape sequences on my Windows console using this functions defined in an header my_windows.h
:
#ifndef WINDOWS_HPP
#define WINDOWS_HPP
namespace osm
{
extern void enableANSI();
extern void disableANSI();
}
and implemented in my_windows.cpp
#ifdef _WIN32
#include <windows.h>
#endif
#include "my_windows.hpp"
#include <iostream>
#include <stdexcept>
namespace osm
{
#ifdef _WIN32
#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#endif
#endif
#ifdef _WIN32
static HANDLE stdoutHandle;
static DWORD outModeInit;
#endif
void enableANSI()
{
#ifdef _WIN32
DWORD outMode = 0;
stdoutHandle = GetStdHandle( STD_OUTPUT_HANDLE );
if( stdoutHandle == INVALID_HANDLE_VALUE )
{
exit( GetLastError() );
}
if( ! GetConsoleMode( stdoutHandle, &outMode ) )
{
exit( GetLastError() );
}
outModeInit = outMode;
outMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if( ! SetConsoleMode( stdoutHandle, outMode ) )
{
exit( GetLastError() );
}
#endif
}
void disableANSI()
{
std::cout << "\033[0m";
#ifdef _WIN32
if( ! SetConsoleMode( stdoutHandle, outModeInit ) )
{
exit( GetLastError() );
}
#endif
}
}
They are used respectively to enable and disable ANSI escape sequences and work well. The problem is that it seems that the function to enable ANSI at the same time disable some Unicode characters, in particular: "\u250c", "\u2500", "\u2510", "\u2502", "\u2502", "\u2514", "\u2500", "\u2518"
which if sent to the output stream show strange symbols instead of their corresponding characters. If I don't use the enableANSI
function the unicode characters works well.
Sorry for the maybe trivial question, but it is the first time I deal with Windows cpp functions.
Thanks.
CodePudding user response:
Thanks to PanagiotisKanavos i solved the issue by using the chcp 65001
command. The problem is that if I am on MSYS2 I am unable to run this command from the shell: therefore I used the system()
function to call it directly in my code, since my executables run directly on the Windows shell:
// code without using ANSI escape sequences...
enableANSI();
// code which uses ANSI escape sequences...
system( "chcp 65001" );
// code which uses ANSI escape sequences and Unicode characters...