Search code examples
c++macoseventssdlkeyboard-events

How to detect keypress in C++ on MacOS?


I'm writing an assignment that needs to show some event-driven programming paradigms so I think key press detection should work fine. I've google for some hours and I've found some solutions for Linux and Windows. Unfortunately, I'm on Mac. So, I've only come up with cross-platform SDL. But I've only worked with Python tkinter for events before but I'm only allowed to use C++ for this assignment. And I'm not really familiar with Xcode as well as C++ so I've no idea how to install SDL into Xcode's C++. Plus, I only need to detect key press, so some smaller library should also work fine. I'm wondering if there is a library that will fulfill my purpose. The program can be as simple as -

while(true){ cout << "The key you pressed was " << pressed_key; }

.


Solution

  • Try this snippet :

    SDL_Event e;
    while (true)
        {
            while (SDL_PollEvent(&e) != 0) {
                if(e.type == SDL_KEYDOWN)
                    cout << "The key you pressed was " << SDL_GetKeyName(e.key.keysym.sym) <<endl;
            }
        }