C语言 移动光标

#include<windows.h>
//下标从1开始,x行y列。
char GetStr(int x, int y)//作用是提取出窗口中第x行y列的位置的字符是什么,如果没有东西会返回空格符号
{
	COORD pos;
	//ReadConsoleOutputCharacterA里的x和y指的是x列y行,且从0开始标号
	pos.X = y - 1; pos.Y = x - 1;
	LPSTR str;
	DWORD read;
	ReadConsoleOutputCharacterA(GetStdHandle(STD_OUTPUT_HANDLE), str, 1, pos, &read);
	return str[0];
}
#include <windows.h>
static void SetPos(int x, int y)
{
	   COORD point = { x, y };//光标要设置的位置x,y
	   HANDLE HOutput = GetStdHandle(STD_OUTPUT_HANDLE);//使用GetStdHandle(STD_OUTPUT_HANDLE)来获取标准输出的句柄
	   SetConsoleCursorPosition(HOutput, point);//设置光标位置
}
这个比system(“cls”)效果好,闪屏不会特别厉害

如果需要清屏,这样调用即可 SetPos(0, 0)
#include<stdio.h>
#include<windows.h>
#include<conio.h>

void MoveCursorTo(int nRows, int nCols) {//在任意位置移动光标
	COORD crdLocation;
	crdLocation.X = nRows;
	crdLocation.Y = nCols;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), crdLocation);
}

int main(int argc, char* argv[])
{
	char chInput = 0;

	int row = 10;
	int col = 10;
	MoveCursorTo(row, col);
	printf("*");

	while (1) {
		//#include<conio.h>中_kbhit可以检测用户是否按下,而_getch可以配合_kbhit拿到用户输入。	
		if (_kbhit() != 0) {//当_kbhit返回值不为0的时候,代表用户有按键按下。
			chInput = _getch();
			switch (chInput) {//只认wasd,其他输入字符不动作
			case'a':
				MoveCursorTo(row, col);//移动到原有的位置,
				printf(" ");//打印空格,覆盖原来打印的字符,
				//Printf()打印都是从左向右的,原来的函数都是先定位(row, col),再打印的"a",这就将"a"覆盖为空格了
				row--;
				MoveCursorTo(row, col);
				printf("a");
				break;
			case'd':
				MoveCursorTo(row, col);
				printf(" ");

				row++;
				MoveCursorTo(row, col);
				printf("d");
				break;
			case'w':
				MoveCursorTo(row, col);
				printf(" ");

				col--;
				MoveCursorTo(row, col);
				printf("w");
				break;
			case's':
				MoveCursorTo(row, col);
				printf(" ");

				col++;
				MoveCursorTo(row, col);
				printf("s");
				break;
			default://其他输入字符不动作
				break;
			}
		}
	}
	return 0;
}

  • 4
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值