在控制台固定位置显示动态数据, 如时间,进度等
主要用到的关键api有两个:
1. GetConsoleScreenBufferInfo
用来获取当前光标位置
2. SetConsoleCursorPosition
用来设置控制台光标位置
示例代码:
#define _AFXDLL #include <afx.h> #include <iostream> using namespace std; int main() { for (int i = 0; i < 10; i++) { printf("*print something*\n"); } cout << "show current time: " << endl; HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO consoleScreenBufferInfo; GetConsoleScreenBufferInfo(hConsole, &consoleScreenBufferInfo); SHORT x = consoleScreenBufferInfo.dwCursorPosition.X; SHORT y = consoleScreenBufferInfo.dwCursorPosition.Y; COORD coordScreen = {x, y}; CTime tm = 0; int sec = 0; int span = 10; while (1) { tm = CTime::GetCurrentTime(); if (sec != tm.GetSecond()){ if (span <= 0) { break; } span--; sec = tm.GetSecond(); SetConsoleCursorPosition(hConsole, coordScreen); printf("%04d-%02d-%02d %02d:%02d:%02d\n", tm.GetYear(), tm.GetMonth(), tm.GetDay(), tm.GetHour(), tm.GetMinute(), tm.GetSecond()); } } cout << "end" << endl; return 0; }