rc-chuah

ClearScreen3

Mar 3rd, 2022 (edited)
814
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.16 KB | None | 0 0
  1. #include <windows.h>
  2.  
  3. void ClearScreen() {
  4.     HANDLE hStdOut;
  5.     hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  6.     // Fetch existing console mode so we correctly add a flag and not turn off others
  7.     DWORD mode = 0;
  8.     if (!GetConsoleMode(hStdOut, &mode))
  9.     {
  10.         return;
  11.     }
  12.     // Hold original mode to restore on exit to be cooperative with other command-line apps.
  13.     const DWORD originalMode = mode;
  14.     mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
  15.     // Try to set the mode.
  16.     if (!SetConsoleMode(hStdOut, mode))
  17.     {
  18.         return;
  19.     }
  20.     // Write the sequence for clearing the display.
  21.     DWORD written = 0;
  22.     PCWSTR sequence = L"\x1b[2J";
  23.     if (!WriteConsoleW(hStdOut, sequence, (DWORD)wcslen(sequence), &written, NULL))
  24.     {
  25.         // If we fail, try to restore the mode on the way out.
  26.         SetConsoleMode(hStdOut, originalMode);
  27.         return;
  28.     }
  29.     // To also clear the scroll back, emit L"\x1b[3J" as well.
  30.     // 2J only clears the visible window and 3J only clears the scroll back.
  31.     // Restore the mode on the way out to be nice to other command-line applications.
  32.     SetConsoleMode(hStdOut, originalMode);
  33. }
Add Comment
Please, Sign In to add comment