1

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.

Jorge Luis
  • 813
  • 6
  • 21

2 Answers2

0

I'm assuming you're using the keyboard module for this. Looking through the code, it seems like that library is event based, so if the CTRL key is pressed before your program starts, then it isn't recognized by the program.

My recommendation would be to read directly from stdin using the sys library. However, looking at How to get Ctrl, Shift or Alt with getch() ncurses?, it seems like CTRL, ALT, and SHIFT don't generate their own input to stdin but rather modify existing input, so you should probably look at using another key as your modifier. You also need a timeout, which Read file with timeout in Python suggests the select module provides. In case you don't know already, sys.stdin is your standard input, and you can treat it like any other file.

WillOw
  • 185
  • 13
  • At the moment it is a code that I can assume that it will be executed in Windows. The win32api library is available for this. It seems to work without a problem. – Jorge Luis Nov 08 '21 at 07:49
0

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:
    ...
Jorge Luis
  • 813
  • 6
  • 21