在控制台中移动光标通常使用ANSI转义序列。以下是一个简单的C语言示例,演示了如何在控制台中移动光标:
```c
include
// 获取光标位置
int wherex() {
CONSOLE_SCREEN_BUFFER_INFO pBuffer;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &pBuffer);
return (pBuffer.dwCursorPosition.X + 1);
}
// 获取光标位置
int wherey() {
CONSOLE_SCREEN_BUFFER_INFO pBuffer;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &pBuffer);
return (pBuffer.dwCursorPosition.Y + 1);
}
// 设置光标位置
void gotoxy(int x, int y) {
COORD c;
c.X = x - 1;
c.Y = y - 1;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
}
int main() {
int x, y;
// 获取当前光标位置
x = wherex();
y = wherey();
printf("Current cursor position: (%d, %d)\n", x, y);
// 移动光标到指定位置
gotoxy(10, 5);
printf("Cursor moved to position (10, 5)\n");
// 获取当前光标位置
x = wherex();
y = wherey();
printf("Current cursor position: (%d, %d)\n", x, y);
return 0;
}
```
解释
获取光标位置
`wherex()` 函数通过 `GetConsoleScreenBufferInfo` 获取控制台屏幕缓冲区信息,并返回光标的 X 坐标(加 1,因为坐标从 0 开始)。
`wherey()` 函数类似地返回光标的 Y 坐标(加 1)。
设置光标位置
`gotoxy(int x, int y)` 函数使用 `SetConsoleCursorPosition` 设置光标的位置。注意坐标需要减 1,因为控制台的坐标从 0 开始。
主函数
在 `main` 函数中,首先获取当前光标位置并打印。
然后使用 `gotoxy` 函数将光标移动到指定位置(例如 (10, 5))。
最后再次获取并打印当前光标位置,以验证光标是否成功移动。
其他光标操作
除了移动光标,还可以使用 ANSI 转义序列来执行其他光标操作,例如:
清除屏幕:`printf("\033[2J")`
上移光标:`printf("\033[%dA", x)`
下移光标:`printf("\033[%dB", x)`
左移光标:`printf("\033[%dD", y)`
右移光标:`printf("\033[%dC", y)`
定位光标:`printf("\033[%d;%dH", x, y)`
隐藏光标:`printf("\033[?25l")`
显示光标:`printf("\033[?25h")`
这些转义序列可以在控制台中使用,但需要注意它们在不同的操作系统和终端中的兼容性。