r/C_Programming • u/AskComprehensive7867 • May 21 '26
Checking inputs efficiently in C
im trying to check inputs in a command line program, using windows api here (runs on command prompt or windows powershell)
if (GetAsyncKeyState(VK_UP))
playerY -= moveSpeed;
else if (GetAsyncKeyState(VK_DOWN))
playerY += moveSpeed;
else if (GetAsyncKeyState(VK_LEFT))
playerX -= moveSpeed;
else if (GetAsyncKeyState(VK_RIGHT))
playerX += moveSpeed;
but is there any way to make it more efficient, 4 system level calls for checking something this trivial is very inefficient? i tried using getkeyboardstate(), but it doesnt work in c. Tried the event driven approach, but it says that it goes through more layers and data structures which brings it back to square one even with low syscalls, im sort of confused
need help pls
4
u/cinnamonjune May 21 '26
If you're making a game you generally want to handle all the inputs as events and then get them into a data structure (an array of booleans) that you can query later.
I would recommend checking out the Kohi game engine series. Don't worry about watching the whole thing and don't worry about the Vulkan stuff if you're not trying to learn that right now. Just focus on the first few videos where he sets up the input system and Windows platform layer. He will show you a good way to handle inputs for a game with Win32 API.
1
u/LateSolution0 May 21 '26
I’m kind of building against the intended use case. Usually on Windows, you get a message queue from your window and dispatch WM_INPUT. Since you’re writing a console application, you have to create a hook with SetWindowsHookEx, but I haven’t really done that in a long time. MSDN is a good resource to learn from.
It’s kind of a bad thing to ask about, because people have written keyloggers this way. Also, I don’t think you ever need WM_INPUT if your app is not in focus. I think overlays do it by injecting a DLL.
1
u/flyingron May 21 '26
Not sure if it is necessarily more "EFFICIENT" but it's arguably more maintainable.
1
u/Sad_Chemical_231 May 21 '26
Use HOTKEY its better for that and there is alot of support online.
1
u/Particular-Ice9109 May 26 '26
Since you are writing a console application, please read input in a console manner.
Reading Input Buffer Events
1
u/[deleted] May 21 '26
[removed] — view removed comment