I made some getch like functions for you :)
Jan 13, 2014 at 8:19pm UTC
Hello Guys i made some functions that let you instantly read characters and keyboard keys.The functions are:
-readchar(Gets the character that you pressed (does not work on keys like arrows,etc) ,the return value is the char that it got)
-readch(Reads key and return ascii code)
-readk(Reads key and return virtualkeycode)
-getk(Reads key and return keyscancode ) - kind of like the original getch()
Here are the functions and i also made a little example :)
P.S : If you dont understand something let me know .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
#include <iostream>
using namespace std;
#include <windows.h>
TCHAR readch() //returns ascii code
{
INPUT_RECORD InputRecord;
DWORD Writtten;
HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
while (true )
{
ReadConsoleInputA(hStdIn,&InputRecord,1,&Writtten);
if (InputRecord.EventType==KEY_EVENT&&InputRecord.Event.KeyEvent.bKeyDown) break ;
}
return InputRecord.Event.KeyEvent.uChar.AsciiChar;
}
SHORT readk() //returns virtualkeycode (you can use VK constants :VK_UP,VK_ESCAPE) to compare
{
INPUT_RECORD InputRecord;
DWORD Writtten;
HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
while (true )
{
ReadConsoleInputA(hStdIn,&InputRecord,1,&Writtten);
if (InputRecord.EventType==KEY_EVENT&&InputRecord.Event.KeyEvent.bKeyDown) break ;
}
return InputRecord.Event.KeyEvent.wVirtualKeyCode;
}
SHORT getk() //returns keyboard scancode
{
INPUT_RECORD InputRecord;
DWORD Writtten;
HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
while (true )
{
ReadConsoleInputA(hStdIn,&InputRecord,1,&Writtten);
if (InputRecord.EventType==KEY_EVENT&&InputRecord.Event.KeyEvent.bKeyDown) break ;
}
return InputRecord.Event.KeyEvent.wVirtualScanCode;
}
int main()
{
cout<<"Enter a character : " ;
char c=readch();
cout<<"\n\n\nYou entered " <<c;
if (c=='a' ) cout<<"\n\n\nAnd btw 'a' is my favorite letter too" ;
cout<<"\n\n\nPress every arrow key" ;
bool uppressed,downpressed,leftpressed,rightpressed;
short k;
while (uppressed+downpressed+leftpressed+rightpressed!=4)
{
k=readk();
if (k==VK_UP) uppressed=true ;
if (k==VK_DOWN) downpressed=true ;
if (k==VK_LEFT) leftpressed=true ;
if (k==VK_RIGHT) rightpressed=true ;
}
cout<<"\n\n\nCongrats you pressed all arrow keys :) !\n" ;
cout<<"\n\n\nNow guess what ?\n" ;
cout<<"Yes you are right : press any key to continue" ;
getk();
return 0;
}
Last edited on Jan 13, 2014 at 9:12pm UTC
Topic archived. No new replies allowed.