I am writing a game in C++, and I need to detect when the user presses a key. Usually, I would use std::cin
, but I have a graphical window, using graphics.h
, a header that was originally provided with the ancient Borland Turbo C++ compiler, but an equivalent is available online. So, I would use the function inportb();
, with a function definition like this:
inline unsigned char inportb(unsigned int port) {
unsigned char ret;
asm volatile ("inb %%dx,%%al":"=a"(ret):"d"(port));
return ret;
}
Source: inportb.
But in Windows, direct low-level hardware I/O like that is protected, and, if it is attempted, the program will be killed. So I need to access that function via a high-level function or API.
My question: How can I do this?
I had a lot of fun with Turbo C++ a few decades ago :-) but if I were you I would try to use a game engine or lib in addition to your C compiler, such as this SDL or Ogre (see https://en.wikipedia.org/wiki/List_of_game_engines for a far too long list).
They provides (among other things) an event loop with keyboards events.
Or at less you may want to use a Windows or cross-platform framework such as the one Microsoft provides with MSVC (which is free for some usage) or Qt (which is even more free and now comes with a convenient IDE).
Have fun writing games that will give fun to others !
There are 4 different ways to detect input in Windows.
If you are attempting to detect the state of a specific key in the middle of your game loop, the GetAsyncKeyState will determine the specific state at that moment.
This function takes a virtual key code (in this case the left arrow key), get the state and after a bitwise AND operation to determine if the key is down, then off you go.
These virtual key codes can be found in WinUser.h. GetAsyncKeyState differs from GetKeyState in that GetKeyState does not reflect the interrupt-level state associated with the hardware (which is why I used GetAsyncKeyState above). If you need all of the key states at a given instance (which is rare), consider GetKeybardState.
However, if you are waiting for a key event (WM_KEYDOWN, WM_CHAR, WM_KEYUP) to occur, you must provide a case in the window procedure to handle that event.
Hope this helps.