Is it possible to pick up the directional keys (famous little keys) from the keyboard? if so how?
Is it possible to pick up the directional keys (famous little keys) from the keyboard? if so how?
In pure C / C ++ you can not do this. To handle the directional keys you must work with a specific API.
You can do this by using the Windows API (Win32) , SDL2 , SFML >, Allegro , Ogre3d , GTK , Qt , wxWidgets and etc., which make the interaction between the operating system and your code.
For example, with SDL
, in the execution loop you would have something like:
SDL_Event event;
while( SDL_PollEvent( &event ) )
{
switch( event.type )
{
case SDL_KEYDOWN:
printf( "Seta para baixo pressionada\n" );
break;
case SDL_KEYUP:
printf( "Seta para cima pressionada\n" );
break;
default:
break;
}
}
Already in wxWidgets
would look something like this:
void MyWin::OnKeyPress(wxKeyEvent& event)
{
long keycode = event.GetKeyCode();
if (keycode == WXK_UP)
{
// Seta para cima pressionada.
event.Skip();
}
}
Already in SFML
is something like:
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
// pressionou para esquerda
}
Ideally, you should choose an API for the project you want to run, because the way each one handles this is a bit different. For example, for games it may be SDL, SFML, Ogre3D. For programs, it can be Qt, wxWidgets, WIN32, GTK and etc.
The main difference is that in game APIs the keys are checked in "real time". In the APIS for the development of desktop programs, keys are treated as events.
One way to do this in Windows is to use Hooks
, which is a technique used to intercept, monitor, and modify the behavior of system calls , functions, messages, and events.
You can detect the directional keys as follows:
#include <Windows.h>
#include <stdio.h>
HHOOK hook;
KBDLLHOOKSTRUCT kbdStruct;
LRESULT __stdcall HookCallback(int nCode, WPARAM wParam, LPARAM lParam){
if ((nCode >= 0) && wParam == WM_KEYDOWN){
kbdStruct = *((KBDLLHOOKSTRUCT*)lParam);
if (kbdStruct.vkCode == VK_LEFT)
puts("A seta da esquerda foi pressionada");
if (kbdStruct.vkCode == VK_RIGHT)
puts("A seta da direita foi pressionada");
if (kbdStruct.vkCode == VK_DOWN)
puts("A seta para baixo foi pressionada");
if (kbdStruct.vkCode == VK_UP)
puts("A seta para cima foi pressionada");
}
return CallNextHookEx(hook, nCode, wParam, lParam);
}
void SetHook(){
if (!(hook = SetWindowsHookEx(WH_KEYBOARD_LL, HookCallback, NULL, 0))){
// Erro ao iniciar o processo de escuta
}
}
int main(){
MSG msg;
SetHook(); // Instala a escuta
while (GetMessage(&msg, NULL, 0, 0)) { }
UnhookWindowsHookEx(hook); // Desinstala a escuta
return 0;
}
When you press the keys:
Documentation
I did in C to pick directional arrows, take a look at this github link: link
Download the entire folder and run the 8-extras.c file and see how it works. The kbhitgetch.pdf file explains and has a good basis for understanding how it works from behind.