I'm new to C programming. Just for fun, I started by trying to create a small game where the player is represented by a letter that can be moved around in the console window.
One of the first obstacles I encountered was that there's no standard way of reading characters from the keyboard in C without waiting for the user to hit the Enter key.
Of course, there's the Getch() function in the conio.h header file, but I'd rather use the Windows API since I'll be working under that OS anyway. After googling, I found that GetKeyState would be the best function for this application (since it's a console app I can't use WM_KEYDOWN, right?).
This is what I have so far:
#include <stdio.h>
#include <windows.h>
#define BITS sizeof(short) * 8
const short MSB = 1 << (BITS - 1);
char get_char(void);
int main(void)
{
char c;
while (1)
{
if (c = get_char()) printf("|%d|%c|\n", c, c);
}
return 0;
}
char get_char(void)
{
int i = 0;
while (i++ < 256) // All keys on the keyboard
{
if (GetKeyState(i) & MSB)
{
while (1) // Waits until the pressed key goes up again
{
if (!(GetKeyState(i) & MSB)) return i;
}
}
}
return 0;
}
The problem I get with this is that the get_char() function doesn't return the correct character. For example, when I press 'a' on the keyboard printf displays 'A'.
I understand that GetKeyState works with Virtual Keys (not ASCII), but is there a way to make the get_char() function to return two values, one VK and one ASCII-value?