C++之光标控制

2021年11月12日 3点热度 0条评论 来源: 丨秋水丨
#include<conio.h>
#include<Windows.h>
#include<iostream>
using namespace std;

#define ESC 0X1B
#define HIGH 0XE0
#define UP 0X48//72
#define LEFT 0X4B//75
#define RIGHT 0X4D//77
#define DOWN 0X50//80

COORD getxy();
void gotoxy(const COORD&);
void hideCursor();

void moveUp();
void moveLeft();
void moveRight();
void moveDown();


int main()
{
	//按上下左右方向键绘图
	hideCursor();
	int ch = 1;
	while ((ch = _getch()) != ESC)     
	{
		if (ch == HIGH)
		{
			ch = _getch();
			switch (ch)
			{
			case UP:
				moveUp();
				cout << ".";
				break;
			case LEFT:
				moveLeft();
				cout << ".";
				break;
			case RIGHT:
				moveRight();
				cout << ".";
				break;
			case DOWN:
				moveDown();
				cout << ".";
			}
			moveLeft();//每一次cout<<".";光标都会向右移,所以最终还要再向左移一次
		}
	}
}

COORD getxy()
{
	HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
	CONSOLE_SCREEN_BUFFER_INFO csbi;
	GetConsoleScreenBufferInfo(handle, &csbi);
	COORD coord;
	coord.X = csbi.dwCursorPosition.X;
	coord.Y = csbi.dwCursorPosition.Y;
	return coord;
}

void gotoxy(const COORD& coord)
{
	HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleCursorPosition(handle, coord);
}

void hideCursor()
{	
	HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
	CONSOLE_CURSOR_INFO cci;
	GetConsoleCursorInfo(handle, &cci);
	cci.bVisible = false;
	SetConsoleCursorInfo(handle, &cci);
}

void moveUp()
{
	COORD coord;
	coord = getxy();
	coord.Y--;
	gotoxy(coord);
}

void moveLeft()
{
	COORD coord;
	coord = getxy();
	coord.X--;
	gotoxy(coord);
}

void moveRight()
{
	COORD coord;
	coord = getxy();
	coord.X++;
	gotoxy(coord);
}

void moveDown()
{
	COORD coord;
	coord = getxy();
	coord.Y++;
	gotoxy(coord);
}

    原文作者:丨秋水丨
    原文地址: https://blog.csdn.net/NONElgh/article/details/72782494
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。