Advertisement
Guest User

Multi-OS clear screen and set console size

a guest
Apr 26th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. void ClearScreen();
  2. bool SetWindow(int,int);
  3.  
  4. int GlobalWidth = 119;
  5. int GlobalHeight = 27;
  6.  
  7. #ifdef _WIN32
  8.  
  9. #include <windows.h>
  10.  
  11. void ClearScreen()
  12. {
  13. SetWindow(GlobalWidth, GlobalHeight);
  14.  
  15. HANDLE hStdOut;
  16. CONSOLE_SCREEN_BUFFER_INFO csbi;
  17. DWORD count;
  18. DWORD cellCount;
  19. COORD homeCoords = { 0, 0 };
  20.  
  21. hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  22. if (hStdOut == INVALID_HANDLE_VALUE) return;
  23.  
  24. /* Get the number of cells in the current buffer */
  25. if (!GetConsoleScreenBufferInfo(hStdOut, &csbi)) return;
  26. cellCount = csbi.dwSize.X *csbi.dwSize.Y;
  27.  
  28. /* Fill the entire buffer with spaces */
  29. if (!FillConsoleOutputCharacter(
  30. hStdOut,
  31. (TCHAR) ' ',
  32. cellCount,
  33. homeCoords,
  34. &count
  35. )) return;
  36.  
  37. /* Fill the entire buffer with the current colors and attributes */
  38. if (!FillConsoleOutputAttribute(
  39. hStdOut,
  40. csbi.wAttributes,
  41. cellCount,
  42. homeCoords,
  43. &count
  44. )) return;
  45.  
  46. /* Move the cursor home */
  47. SetConsoleCursorPosition(hStdOut, homeCoords);
  48. }
  49.  
  50.  
  51. bool SetWindow(int Width, int Height)
  52. {
  53. _COORD coord;
  54. coord.X = Width;
  55. coord.Y = Height;
  56.  
  57. _SMALL_RECT Rect;
  58. Rect.Top = 0;
  59. Rect.Left = 0;
  60. Rect.Bottom = Height - 1;
  61. Rect.Right = Width - 1;
  62.  
  63. // Get handle of the standard output
  64. HANDLE Handle = GetStdHandle(STD_OUTPUT_HANDLE);
  65. if (Handle == NULL)
  66. {
  67. cout << "Failure in getting the handle\n" << GetLastError();
  68. return FALSE;
  69. }
  70.  
  71. // Set screen buffer size to that specified in coord
  72. if (!SetConsoleScreenBufferSize(Handle, coord))
  73. {
  74. cout << "Failure in setting buffer size\n" << GetLastError();
  75. return FALSE;
  76. }
  77.  
  78. // Set the window size to that specified in Rect
  79. if (!SetConsoleWindowInfo(Handle, TRUE, &Rect))
  80. {
  81. cout << "Failure in setting window size\n" << GetLastError();
  82. return FALSE;
  83. }
  84.  
  85. return TRUE;
  86. }
  87.  
  88.  
  89. #else
  90.  
  91. void ClearScreen()
  92. {
  93. SetWindow(GlobalWidth, GlobalHeight);
  94.  
  95. std::cout << "\033[2J\033[1;1H";
  96. std::cout << "\033[2J\033[1;1H";
  97. }
  98.  
  99. bool SetWindow(int width, int height)
  100. {
  101. string res = "\e[8;";
  102. res += to_string(height);
  103. res += ";";
  104. res += to_string(width);
  105. res += "t";
  106. cout << res;
  107. return true;
  108. }
  109.  
  110. #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement