How to pick up the arrow keys in C/C++?

Asked

Viewed 5,076 times

6

Is it possible to pick up the arrow keys (famous arrow keys) from the keyboard? if yes, how?

3 answers

9


In pure C/C++ you can’t do that. To handle 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 etc, that make the interaction between the operating system and its 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 the wxWidgets it would be something like that:

void MyWin::OnKeyPress(wxKeyEvent& event)
{
    long keycode = event.GetKeyCode();
    if (keycode == WXK_UP)
    {
        // Seta para cima pressionada.
        event.Skip();
    }
}

Already in the SFML is something like:

if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
    // pressionou para esquerda
}

Ideally, you should choose your own API for the project you want to run, because the way each of them treats this is a little different. For example, for games it can be SDL, SFML, Ogre3d. For programs, it can be Qt, wxWidgets, WIN32, GTK, etc.

The main difference is that in the game Apis the keys are checked in "real time". In the APIS for developing desktop programs, the keys are treated as events.

  • have some example?

  • 1

    I’ll edit my reply and add.

  • 1

    I remember the time that it was done capturing interruptions, without API or anything... but we are talking about MS-DOS :)

  • I think you could pick up the directional arrows with the conio.h.

  • 1

    as there is no way to do in pure C if the tools listed above are made in pure C ?

  • 2

    Please edit your answer. There are ways to do it in Linguem C. Including some tools that Oce mentioned are totally based on C language.

Show 1 more comment

4

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;
}

By pressing the keys:

inserir a descrição da imagem aqui

Documentation

  • 2

    But for the use of Hooks you had to use the Windows API. It would be pure even if there were something like: std::cin.get() == KEY_LEFT.

  • -1: SetWindowsHookEx it’s neither C nor C++.

  • @pepper_chico Negative a correct answer that can help those who need it by pedantry? OK, it’s in your right, but..

  • corrected, removed. @Guilhermebernal I am not in favor of spreading misinformation, even if they are useful by devious means.

2

I did in C to pick up directional arrows, take a look at this link from github: https://github.com/CarlosAdir/C-Programs/tree/master/Tutoriais

Download the entire folder and run the 8-extras file. c and see how it works. The kbhitgetch.pdf file explains and has a good basis for understanding how it works behind.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.