Created
November 20, 2021 13:44
-
-
Save XiaoPanPanKevinPan/b95897da3d573d8eefc33ebb1285ec66 to your computer and use it in GitHub Desktop.
C 語言用 ANSI 轉義序列在 Windows 上移動光標
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <wchar.h> | |
#include <windows.h> | |
void enableAnsiSqeuence(){ | |
HANDLE hStdin; | |
hStdin = GetStdHandle(STD_INPUT_HANDLE); | |
/* 參考: https://docs.microsoft.com/en-us/windows/console/setconsolemode */ | |
const int ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200; | |
SetConsoleMode(hStdin, ENABLE_VIRTUAL_TERMINAL_INPUT); | |
} | |
/* 一些使用 ANSI 轉義序列的函數 | |
* 參考: https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences | |
* | |
* "\x1b" 代表 ESC | |
*/ | |
void term_clear(){ | |
//printf("\x1b[H\x1b[J"); | |
system("cls"); | |
} | |
void term_cursor_gotoXY(int x, int y){ | |
wprintf(L"\x1b[%d;%dH", y, x); | |
} | |
void term_cursor_moveXY(int x, int y){ | |
if(y > 0){ | |
wprintf(L"\x1b[%dB", y); // 下移 |x| 格 | |
}else if(y < 0){ | |
wprintf(L"\x1b[%dA", -y); // 上移 |x| 格 | |
} // 若 y == 0 則不上下移 | |
if(x > 0){ | |
wprintf(L"\x1b[%dD", x); // 右移 |x| 格 | |
}else if(x < 0){ | |
wprintf(L"\x1b[%dC", -x); // 左移 |x| 格 | |
} // 若 x == 0 則不左右移 | |
} | |
void term_cursor_gotoLineHead(){ | |
printf("\r"); | |
} | |
int main(void) | |
{ | |
enableAnsiSqeuence(); | |
term_clear(); | |
int age; | |
char name[51]={'\0'}, gender[51]={'\0'}; | |
printf("%50s: \n", "How old are you"); | |
printf("%50s: \n", "What's your name (less than 50 char)"); | |
printf("%50s: \n", "And what's your gender (less than 50 char)"); | |
term_cursor_gotoXY(53, 1); | |
scanf("%d", &age); | |
term_cursor_gotoXY(53, 2); | |
scanf("%s", name); | |
term_cursor_gotoXY(53, 3); | |
scanf("%s", gender); | |
term_cursor_gotoXY(1, 5); | |
printf("So you're %s, right?\nAnd you're %d old, considering yourself a %s person.\n\n", name, age, gender); | |
system("pause"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment