Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to input key up, key down, key left and key right key pressed events in SDL2 with C

1 Answer

0 votes
#include <stdio.h>
#include <stdbool.h>
#include <SDL.h>

static SDL_Window* window = NULL;

bool init() {
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        printf("SDL_Init Error: %s\n", SDL_GetError());
        return false;
    }
    else {
        window = SDL_CreateWindow("SDL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                    800, 600, SDL_WINDOW_SHOWN);
        if (window == NULL) {
            printf("SDL_CreateWindow Error: %s\n", SDL_GetError());
            return false;
        }
    }

    return true;
}

void close() {
    SDL_DestroyWindow(window);
    window = NULL;

    SDL_Quit();
}

int main(int argc, char* argv[]) {
    if (!init()) {
        printf("init error\n");
    }
    else {
        SDL_Event event;
        bool quit = false;
        while (quit == false) {
            while (SDL_PollEvent(&event)) {
                if (event.type == SDL_QUIT) {
                    quit = true;
                }
                else if (event.type = SDL_KEYDOWN) {
                    switch (event.key.keysym.sym) {
                        case SDLK_UP:
                            SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "SDL2", "SDLK_UP", window);
                            break;
                        case SDLK_DOWN:
                            SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "SDL2", "SDLK_DOWN", window);
                            break;
                        case SDLK_LEFT:
                            SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "SDL2", "SDLK_LEFT", window);
                            break;
                        case SDLK_RIGHT:
                            SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "SDL2", "SDLK_RIGHT", window);
                            break;
                    }
                }
            }
        }
    }
    close();

    return 0;
}

 



answered Jul 25, 2023 by avibootz
...