Skip to content

Instantly share code, notes, and snippets.

@njsmith
Created August 25, 2022 21:43
Show Gist options
  • Save njsmith/9cf1e9929947c6b7bb0ab330323beef4 to your computer and use it in GitHub Desktop.
Save njsmith/9cf1e9929947c6b7bb0ab330323beef4 to your computer and use it in GitHub Desktop.
import sys
import msvcrt
import ctypes
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
kernel32.GetConsoleMode.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint)]
kernel32.GetConsoleMode.restype = ctypes.c_int
kernel32.SetConsoleMode.argtypes = [ctypes.c_void_p, ctypes.c_uint]
kernel32.SetConsoleMode.restype = ctypes.c_int
def GetConsoleMode(handle):
flags = ctypes.c_uint(0)
ok = kernel32.GetConsoleMode(handle, ctypes.byref(flags))
if not ok:
raise ctypes.WinError()
return flags.value
def SetConsoleMode(handle, flags):
ok = kernel32.SetConsoleMode(handle, flags)
if not ok:
raise ctypes.WinError()
# Can fail if sys.stdout has no fileno
console = msvcrt.get_osfhandle(sys.stdout.fileno())
flags = GetConsoleMode(console)
print(f"old flags = {flags:x}")
print("\033[1;31mtext\033[0;0m")
SetConsoleMode(console, flags | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
# Check whether it worked
flags = GetConsoleMode(console)
print(f"new flags = {flags:x}")
print("\033[1;31mtext\033[0;0m")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment