Is there a function that can perform like getch() without having to #include <conio.h>
Basically I am working on a console game and I am moving the so called sprite character with the arrow keys. I declared an integer key in the global scope and used it within the local scope inside the do while loop assigning it with getch().
Here is a demonstration of the piece of snippet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <Windows.h>
#include <iostream>
#include <conio.h>
int key;
int main(){
do{
key = getch();
switch(key){
case RIGHT:
gotoXY(x, y);
std::cout<<' ';
x++;
gotoXY(x, y);
std::cout<<((char)('\x01'));
break;
}
return 0;
}
I just want to know if it is possible to avoid including another directive that acts like getch thats maybe in <Windows.h> or <iostream>?
Not really understanding those forums. Here is what I tried with an updated version of my partial code I am displaying, while it still compiles with no errors, but no success.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
HANDLE h = GetStdHandle(STD_INPUT_HANDLE);
DWORD keyPress;
INPUT_RECORD buffer;
PeekConsoleInput(h,&buffer,1, &keyPress);
do{
ReadConsoleInput(h,&buffer,1, &keyPress);
//keyPress = _getch(); //Use getch() if compiling error
if(keyPress == RIGHT){ //Move player right
sprite->GotoXY(sprite->posX,sprite->posY);
sprite->posX++;
sprite->GotoXY(sprite->posX,sprite->posY);
sprite->Player();
}
#include <windows.h>
#include <iostream>
int main(){
DWORD dword;
INPUT_RECORD keyPress; //Input Event
HANDLE handle = GetStdHandle(STD_INPUT_HANDLE);
BOOL escape = FALSE; //Used to escape
GetConsoleMode(handle, &dword);
SetConsoleMode(handle, 0);
std::cout<<"Press UP DOWN LEFT (or) RIGHT Key as many times.\n""Press ESC to quit.\n\n";
while (!escape){
if (WaitForSingleObject( handle, 0 ) == WAIT_OBJECT_0){
ReadConsoleInput( handle, &keyPress, 1, &dword );
/* Only respond to key release events */
if((keyPress.EventType == KEY_EVENT)
&&
!keyPress.Event.KeyEvent.bKeyDown){
switch (keyPress.Event.KeyEvent.wVirtualKeyCode){
case VK_UP:
std::cout<<"You Pressed: UP Key"<<std::endl;
break;
case VK_DOWN:
std::cout<<"You Pressed: DOWN Key"<<std::endl;
break;
case VK_RIGHT:
std::cout<<"You Pressed: RIGHT Key"<<std::endl;
break;
case VK_LEFT:
std::cout<<"You Pressed: LEFT Key"<<std::endl;
break;
case VK_ESCAPE:
escape = TRUE;
break;
default:
std::cout<<
"I am not programmed to record that key..."
<<std::endl;
}
}
}
}
SetConsoleMode(handle, dword);
return 0;
}