I'm getting use to the basics of game programming and design. I'm currently trying to practice with using the command line to render images for a platformer by looping the screen output. I just want to make a few simple projects, e.g clock, tetris, cellular automata(looking forward to Game of Life ¯\_(ツ)_/¯ ), etc before using any advanced libraries or going into something like Unity®.
I used the GetAsyncKeyState(VK_key)
function I found from various online resources to control the player with the arrow keys. This works, in fact a little too well. It has the unintended effect of controlling the player even when the program is in the background/ not in focus/ inactive.
So how do I CONSTANTLY get keyboard button states/input ONLY while program is in focus?
I've looked for various solutions, one of which was the first answer
here.
It required me knowing the process id of the program, to which I tried variants of (I only used one at a time):
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdbool.h>
#ifdef _WIN32
#include <Windows.h>
#define SLEEP(x) Sleep(x) // takes milliseconds(ms)
#else
#include <unistd.h>
#define SLEEP(x) usleep(x * 1000) // takes microseconds(μs)
#endif
void printInColour(char str[], unsigned short colour) {
HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hcon, colour);
printf("%s", str);
SetConsoleTextAttribute(hcon, 7); // Set back to default.
}
bool key_pressed(int key) {
return (GetAsyncKeyState(key) != 0);
}
bool IsForegroundProcess()
{
HWND hwnd = GetForegroundWindow();
if (hwnd == NULL) return false;
DWORD foregroundPid;
if (GetWindowThreadProcessId(hwnd, &foregroundPid) == 0) return false;
//return true;
//return (foregroundPid == GetProcessId( GetStdHandle(STD_OUTPUT_HANDLE)));
//return ( foregroundPid == getpid() );
//return (foregroundPid == GetCurrentProcessId());
//return (foregroundPid == GetProcessIdOfThread(GetStdHandle(STD_OUTPUT_HANDLE) ));
return (foregroundPid == GetThreadId( GetStdHandle(STD_OUTPUT_HANDLE)));
}
void main() {
// ...
while(isRunning) {
//...
if (IsForegroundProcess())
printInConsole(">> Currently Active\n", 10); // Debug in green
else
printInConsole(">> Return to focus\n", 12); // ...and red
if (key_pressed(VK_UP) != 0) {/*...*/} // jump, etc
SLEEP(1000);
}
}
I edited the code to remove the actual game. The fix I tried constantly fails saying it's out of focus. I'm open to any suggestions of how to get key pressed info(but only when program is in focus/active). Also, any tips for a newcomer into this daunting world of creating games will be vastly appreciated.