#X11 get keypress not working

9 messages · Page 1 of 1 (latest)

bold pollen
#

I have this piece of code taken from here: https://stackoverflow.com/questions/18281412/check-keypress-in-c-on-linux

#include <X11/Xlib.h>
#include <iostream>
#include "X11/keysym.h"

bool key_is_pressed(KeySym ks) {
    Display *dpy = XOpenDisplay(":0");
    char keys_return[32];
    XQueryKeymap(dpy, keys_return);
    KeyCode kc2 = XKeysymToKeycode(dpy, ks);
    bool isPressed = !!(keys_return[kc2 >> 3] & (1 << (kc2 & 7)));
    XCloseDisplay(dpy);
    return isPressed;
}

int main(int argc, char **argv) {
    while (1) {
        if (key_is_pressed(XK_Control_L)) {
            std::cout << "left control pressed" << std::endl;
        }
    }
    return 0;
};

compiled with

g++ main.cpp -lX11

when I run the program the desired string doesn't get printed when I press left control

quick eagleBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For more information use !howto ask.

craggy epoch
#

did you highlight the window?

bold pollen
#

do you mean that the window wasn't focused?

craggy epoch
#

just double checking

bold pollen
#

i had the window and display focused, although I am in a VM, could that cause any problems?

craggy epoch
#

No clue

#

But I remember having to manually press the window to be able to detect keypresses

quick eagleBOT
#

This question thread is being automatically closed. If your question is not answered feel free to bump the post or re-ask. Take a look at !howto ask for tips on improving your question.