1_bug
1_bug

Reputation: 5717

C++ Move cursor in console

I'm using Visual Studio 2010 and I'm trying move cursor when user press right-array key on keyboard:

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

It's working but just once - second, third etc. pressed not working.

Upvotes: 3

Views: 8050

Answers (4)

chunkyPug
chunkyPug

Reputation: 3

The code below should work! :)

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

Upvotes: 0

George Matei Popa
George Matei Popa

Reputation: 1

For the up, right, left, down you can make "Keys" a char value instead of int and in that case you can move with the keys "w" for up, "s" for down, "a" for left and "d" for right:

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

Upvotes: 0

Sergey
Sergey

Reputation: 8238

You never change poz_x in your code. In your while loop you always move to the initial value +1. A code like this should be correct:

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

Upvotes: 3

Yakov Galka
Yakov Galka

Reputation: 72449

You never change poz_x, so you always end up calling

gotoxy(2,1);

in the loop.

Upvotes: 1

Related Questions