DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Unleashing the Power of Hackathons: A Must for Senior and Middle Developers
  • Why Software Development Leaders Should Invest in Continuous Learning and Growth Opportunities
  • Building Real-Time Applications to Process Wikimedia Streams Using Kafka and Hazelcast
  • Reactive Event Streaming Architecture With Kafka, Redis Streams, Spring Boot, and HTTP Server-Sent Events (SSE)

Trending

  • Microservices With Apache Camel and Quarkus
  • What Is a Flaky Test?
  • AWS ECS vs. Kubernetes: The Complete Guide
  • Backend For Frontend (BFF) Pattern

Handling Keyboard and Mouse Events in SDL2

Trying to decipher keyboard and mouse events in SDL2? Here's how to handle them.

Daniel D'agostino user avatar by
Daniel D'agostino
·
Nov. 16, 15 · Tutorial
Like (2)
Save
Tweet
Share
10.30K Views

Join the DZone community and get the full member experience.

Join For Free

hi there! in this article, we’ll learn how to handle keyboard and mouse events, and we’ll use them to move an object around the window. hooray!

we’ll start with an image. i made this 64×64 bitmap:

spaceship

as you can see, i can’t draw to save my life. but since this is a bitmap, we don’t need the sdl_image extension.

once you have an image, you’ll want to create a new visual studio project, wire it up to work with sdl2, and then add some code to display a window and the spaceship in it. if you don’t remember how, these past articles should help:

  1. “ setting up sdl2 with visual studio 2015 “
  2. “ showing an empty window in sdl2 “
  3. “ displaying an image in an sdl2 window “

you should end up with code that looks something like this:

#include <sdl.h>

int main(int argc, char ** argv)
{
    // variables

    bool quit = false;
    sdl_event event;
    int x = 288;
    int y = 208;

    // init sdl

    sdl_init(sdl_init_video);
    sdl_window * window = sdl_createwindow("sdl2 keyboard/mouse events",
        sdl_windowpos_undefined, sdl_windowpos_undefined, 640, 480, 0);
    sdl_renderer * renderer = sdl_createrenderer(window, -1, 0);

    sdl_surface * image = sdl_loadbmp("spaceship.bmp");
    sdl_texture * texture = sdl_createtexturefromsurface(renderer,
        image);
    sdl_freesurface(image);

    sdl_setrenderdrawcolor(renderer, 255, 255, 255, 255);

    // handle events

    while (!quit)
    {
        sdl_waitevent(&event);

        switch (event.type)
        {
        case sdl_quit:
            quit = true;
            break;
        }

        sdl_rect dstrect = { x, y, 64, 64 };

        sdl_renderclear(renderer);
        sdl_rendercopy(renderer, texture, null, &dstrect);
        sdl_renderpresent(renderer);
    }

    // cleanup sdl

    sdl_destroytexture(texture);
    sdl_destroyrenderer(renderer);
    sdl_destroywindow(window);
    sdl_quit();

    return 0;
}

you’ll also want to place spaceship.bmp into your debug folder (along with sdl2.dll ) so that the program can find the files it needs..

once you actually run the program, you should see this:

sdl2-kbd-kickoff

i set the window’s background to white to match the spaceship’s white background by setting the clear colour using sdl_setrenderdrawcolor() , and then calling sdl_renderclear() to clear the window to that colour.

in order to handle keyboard and mouse events, we need an sdl_event . well, what do you know: we have been using one all along, in order to take action when the window is closed. what we need now is to handle a different event type. so let’s add a new case statement after the one that handles sdl_quit :

            case sdl_keydown:

                break;

within this case statement, let us now determine which key was actually pressed, and move the spaceship accordingly:

            case sdl_keydown:
                switch (event.key.keysym.sym)
                {
                    case sdlk_left:  x--; break;
                    case sdlk_right: x++; break;
                    case sdlk_up:    y--; break;
                    case sdlk_down:  y++; break;
                }
                break;

if you now run the program, you’ll find that you can move the spaceship using the arrow keys:

sdl2-kbd-moving-slow

you’ll notice that it seems to move pretty slowly, and you have to keep pressing for quite a while to make any significant movement. now, in your code, replace sdl_waitevent with sdl_pollevent :

now, try running it again:

sdl2-kbd-moving-fast

swoosh! in less than half a second, the spaceship hits the edge of the window. it’s actually too fast. to get this down to something manageable, add a small delay at the beginning of your while loop:

        sdl_delay(20);

sdl_pollevent() is better than sdl_waitevent() when you want to continuously check (i.e. poll ) for events, but it consumes more cpu power (you can see this if you open task manager). sdl_waitevent() is okay when your window is mostly sitting idle so you don’t need to check for events that often.

handling mouse events is also very easy. all you need to do is handle the appropriate event. let’s see how to handle a mouse click:

            case sdl_mousebuttondown:
                switch (event.button.button)
                {
                    case sdl_button_left:
                        sdl_showsimplemessagebox(0, "mouse", "left button was pressed!", window);
                        break;
                    case sdl_button_right:
                        sdl_showsimplemessagebox(0, "mouse", "right button was pressed!", window);
                        break;
                    default:
                        sdl_showsimplemessagebox(0, "mouse", "some other button was pressed!", window);
                        break;
                }
                break;

and this is what happens when you run it, and click somewhere in the window:

sdl2-kbd-left-click

you can also track mouse motion and obtain the current coordinates of the mouse pointer. this is useful when moving things with the mouse (e.g. moving an object by mouse-dragging it). the following code obtains the mouse coordinates and displays them in the window title:

            case sdl_mousemotion:
                int mousex = event.motion.x;
                int mousey = event.motion.y;

                std::stringstream ss;
                ss << "x: " << mousex << " y: " << mousey;

                sdl_setwindowtitle(window, ss.str().c_str());
                break;

note that you’ll need to add the following at the top of your main.cpp to make the above code work:


#include <sstream>

you will now notice the mouse coordinates in the window title:

sdl2-kbd-mouse-coords

wonderful! you should now have an idea of how to capture and handle keyboard and mouse events in sdl2. we will see more of these in an upcoming article dealing with drawing pixels in the window, so stay tuned to learn more!

this article was originally posted as “ sdl2: keyboard and mouse movement (events) ” at programmer’s ranch on 12th february 2014. it is slightly updated here. the source code and spaceship bitmap are available at the gigi labs bitbucket repository .

Event

Published at DZone with permission of Daniel D'agostino, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Unleashing the Power of Hackathons: A Must for Senior and Middle Developers
  • Why Software Development Leaders Should Invest in Continuous Learning and Growth Opportunities
  • Building Real-Time Applications to Process Wikimedia Streams Using Kafka and Hazelcast
  • Reactive Event Streaming Architecture With Kafka, Redis Streams, Spring Boot, and HTTP Server-Sent Events (SSE)

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: