Search code examples
pythonkeyboard

Check key pressed before begin script


I want my configuration menu to open at the start of a script if the Ctrl key is being pressed. That is, the user would start pressing the key before the script starts running. To intercept that I have tried keyboard.is_pressed('ctrl'), but it always returns false.

I have also tried keyboard.read_key but this method gives me two problems: If it is not pressed, the program does not continue running. If it is pressed, it just continues running only when I release the control key.

Maybe I just need to think of another way to open this menu.


Solution

  • Assuming my code is going to run on Windows and thanks to my experience in C++ I came up with the win32api module.

    # Windows module to controll the keyboard
    import win32api
    # Windows module with every key code
    import win32con
        
    # Check whether the control key is pressed
    if win32api.GetAsyncKeyState(win32con.VK_CONTROL) & 0x8000 > 0:
        ...