C ++在控制台中移动光标

问题描述 投票:1回答:3

我正在使用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;
}

它正在工作,但是只有一次-第二,第三等按不起作用。

c++ winapi console-application keyboard-events
3个回答
0
投票

您永远不会更改poz_x,所以您总是会打电话给您

gotoxy(2,1);

循环中。


3
投票

您从不更改代码中的poz_x。在while循环中,您始终移至初始值+1。这样的代码应该是正确的:

while(true)
{   
    Keys = getch();
    if (Keys == 77)
    {
            poz_x+=1;     
            gotoxy(poz_x,poz_y);
    }
}

0
投票

对于上,右,左,下,您可以将“键”设为char值而不是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);
                }
}
© www.soinside.com 2019 - 2024. All rights reserved.