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;
}

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

4

4 回答 4

3

你永远不会改变poz_x你的代码。在你的 while 循环中,你总是移动到初始值 +1。像这样的代码应该是正确的:

while(true)
{   
    Keys = getch();
    if (Keys == 77)
    {
            poz_x+=1;     
            gotoxy(poz_x,poz_y);
    }
}
于 2013-01-18T18:04:04.390 回答
1

你从不改变poz_x,所以你总是打电话

gotoxy(2,1);

在循环。

于 2013-01-18T18:03:32.543 回答
0

对于上、右、左、下,您可以将“Keys”设置为 char 值而不是 int,在这种情况下,您可以使用键“w”移动,“s”移动,“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);
                }
}
于 2019-11-16T20:52:37.307 回答
0

下面的代码应该可以工作!:)

#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);
       }
   }
}
于 2021-01-14T00:58:32.520 回答