使用 SetConsoleCursorPosition 實現座標定位輸出,構建動態進度條演示,展示控制台句柄、光標屬性、座標結構體的綜合應用。
| 函數/結構體 | 用途 |
|---|---|
| GetStdHandle(STD_OUTPUT_HANDLE) | 獲取標準輸出句柄 |
| COORD {X, Y} | 座標結構體,原點(0,0)左上角 |
| SetConsoleCursorPosition(hOut, pos) | 設置光標位置 |
| CONSOLE_CURSOR_INFO | 光標大小/可見性控制 |
| SetConsoleTextAttribute | 設置文本顏色屬性 |
| Sleep(ms) | 毫秒級延遲 |
#include
#include
#include
int main() {
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos = {0, 0};
// 隱藏光標
CONSOLE_CURSOR_INFO cci;
GetConsoleCursorInfo(hOut, &cci);
cci.bVisible = FALSE;
cci.dwSize = 1;
SetConsoleCursorInfo(hOut, &cci);
// 設置顏色:紅色前景 + 藍色背景 + 高亮
SetConsoleTextAttribute(hOut, 0x0004 | 0x0008 | 0x8000);
// 定位輸出
pos.X = 5; pos.Y = 5;
SetConsoleCursorPosition(hOut, pos);
printf("我在這裡%2d%%", 0);
// 動態進度條
pos.X = 13; pos.Y = 5;
for (int i = 0; i <= 100; i++) {
SetConsoleCursorPosition(hOut, pos);
printf("%2d%%", i);
Sleep(500);
}
getch();
return 0;
}
0x8000 為高亮/加粗Linux/Unix 使用 ANSI 轉義序列或 ncurses 庫:
printf("\033[%d;%dH", row, col); // ANSI 定位
// 或 ncurses: move(y, x);
掌握平台原生 API,是系統級工具開發的基礎。