I wrote a Python script that performs simple actions based on what I press on my keyboard. The script always works perfectly, except when Visual Studio Code is open and active. It's like VSCode is catching the pressed keys BEFORE my python script. If I close VSCode, or just minimize the window, and another window is active, my python script works again.
VSCode does not "steal" the keys only from python scripts, it steals them from other applications as well. For example, when VSCode window is active, I can not use my OBS shortcut for start recording. I tried to lower VSCode priority and increase my python script priority, but it did not work.
Does anyone know how can I make my python script catch the pressed keys, before VSCode steals them?
EDIT: Please find below a minimum reproducible example. The following script prints an a when the a key is pressed on the keyboard. It works with any active window, except VSCode. In fact, when VSCode window is active it stops working. Tests done in Windows 10.
from keyboard import is_pressed
from time import sleep
while True:
if is_pressed('a'):
print('a')
sleep(0.2)
CodePudding user response:
I have found the solution!
I noticed that my VSCode was set to always run as administrator. I set this option months ago, and somehow persisted even after completely uninstalling and reinstalling VSCode.
I just disabled the option and now it works! Thank you ColdFish and MingJie for all of your help.
CodePudding user response:
Thanks for the detail Jeffrey. I could not reproduce the issue on a reasonably fresh install of VSCode, also on Windows 10.
I looked through the documentation in the readme of the keyboard package and found this in the "Known Limitations" section:
Other applications, such as some games, may register hooks that swallow all key events. In this case keyboard will be unable to report events.
I'm going to hazard a guess that one of your VSCode plugins is registering a hook to capture key events. I suspect that if you try it on a fresh VSCode installation (which will be similar to mine) it may work.
Alternatively, you can try using another similar implementation in pynput
of the same functionality. That may work without any alterations to VSCode. A minimum example is here that will mirror the functionality of your minimum example:
from pynput.keyboard import Key, Listener, KeyCode
def on_press(key):
if key == KeyCode.from_char('a'):
print('{0} pressed'.format(key))
while True:
with Listener(on_press=on_press) as listener:
listener.join()
You can find further documentation on how to handle the keyboard with pynput
here.