简体   繁体   中英

SDL2 keyboard detection doesn't work

I try to make a simple game using sdl2 for handling keyboard events. But the main problem is that neither in Clion embedded console nor in external console my program can't detect any event, only SDL_AUDIODEVICEADDED is caught twice at start of the program. Here's my code:

#include <iostream>
#include "include/SDL2/SDL_keyboard.h"
#include "include/SDL2/SDL_keycode.h"
#include "include/SDL2/SDL_scancode.h"

#include "include/SDL2/SDL.h"

using namespace std;

int main(int argc, char* argv []) {
    SDL_Event event;
    bool running = true;
    SDL_Init(SDL_INIT_EVERYTHING);
    int x, y;
    while(running){

        if(SDL_PollEvent(&event)){
            switch(event.type){
                case SDL_QUIT: running = false; break; 
                case SDL_KEYDOWN: 
                    switch(event.key.keysym.sym){ 
                        case SDLK_q: 
                            running = false;
                            break; 
                    }
                    break;

                case SDL_MOUSEBUTTONDOWN:
                    SDL_GetMouseState(&x, &y); 
                    cout << "[SDL_MOUSEBUTTONDOWN] " << "x = " << x << " y = " << y << "\n";
                    break;
                case SDL_MOUSEMOTION:
                    x = event.motion.x;
                    y = event.motion.y;
                    cout << "[SDL_MOUSEMOTION] " << "x = " << x << " y = " << y << "\n";
                    break;
            }
        }
    }
}

SDL_Init returns 0.

You need to create a window.

Keyboard and mouse events depend on a display surface. Only mouse actions within a window and keyboard input while the window is in focus will be captured. After all, you shouldn't be able to receive input possibly directed at other applications.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM