[英]C++ Move cursor in console
我正在使用 Visual Studio 2010,当用户按下键盘上的右阵列键时,我正在尝试移动光标:
#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
void gotoxy(int x, int y)
{
static HANDLE h = NULL;
if(!h)
h = GetStdHandle(STD_OUTPUT_HANDLE);
COORD c = { x, y };
SetConsoleCursorPosition(h,c);
}
int main()
{
int Keys;
int poz_x = 1;
int poz_y = 1;
gotoxy(poz_x,poz_y);
while(true)
{
fflush(stdin);
Keys = getch();
if (Keys == 77)
gotoxy(poz_x+1,poz_y);
}
cin.get();
return 0;
}
它正在工作,但只有一次 - 第二次,第三次等按不工作。
你永远不会在你的代码中改变poz_x
。 在你的 while 循环中,你总是移动到初始值 +1。 像这样的代码应该是正确的:
while(true)
{
Keys = getch();
if (Keys == 77)
{
poz_x+=1;
gotoxy(poz_x,poz_y);
}
}
你永远不会改变poz_x
,所以你最终总是打电话
gotoxy(2,1);
在循环。
对于向上,向右,向左,向下,您可以将“Keys”设为字符值而不是 int,在这种情况下,您可以使用“w”向上移动,“s”向下移动,“a”向左移动和“ d" 为右:
char Keys;
while(true){
Keys = getch();
if (Keys == 'd'){
poz_x+=1;
gotoxy(poz_x,poz_y);
}
if(Keys=='w'){
poz_y-=1;
gotoxy(poz_x,poz_y);
}
if(Keys=='s'){
poz_y+=1;
gotoxy(poz_x,poz_y);
}
if(Keys=='a'){
poz_x-=1;
gotoxy(poz_x,poz_y);
}
}
下面的代码应该可以工作! :)
#include <windows.h>
using namespace std;
POINT p;
int main(){
while(true){
GetCursorPos(&p);
Sleep(1);
int i = 0;
if(GetAsyncKeyState(VK_RIGHT)){
i++;
SetCursorPos(p.x+i, p.y);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.