I'm trying to do what this question asked (this question has no valid answers with functional code using pynput
): Press Windows+D with pynput
. But, my attempts are not working as expected.
On Linux Ubuntu, pressing Windows + d will minimize all windows, thereby showing the desktop. Doing it again will bring all the windows back as they were.
Here's my code:
import time
from pynput.keyboard import Key, Controller
keyboard = Controller()
SUPER_KEY = Key.cmd
keyboard.press(SUPER_KEY)
# time.sleep(1)
keyboard.press('d')
keyboard.release('d')
keyboard.release(SUPER_KEY)
When I run it, I expect the Windows + d shortcut to be pressed, hiding all windows. Instead, only the Windows key is pressed, which brings up the program launcher search tool, and then a single d
is left printed in my terminal, like this:
$ ./pynput_press_Windows+D_to_show_the_desktop.py
$ d
How do I get this to work?
The reference documentation says (https://pynput.readthedocs.io/en/latest/keyboard.html) that Key.cmd
is the "Super" or "Windows" key. I've also tried with Key.cmd_l
and Key.cmd_r
.
cmd
= 0A generic command button. On PC platforms, this corresponds to the Super key or Windows key, and on Mac it corresponds to the Command key. This may be a modifier.
cmd_l
= 0The left command button. On PC platforms, this corresponds to the Super key or Windows key, and on Mac it corresponds to the Command key. This may be a modifier.
cmd_r
= 0The right command button. On PC platforms, this corresponds to the Super key or Windows key, and on Mac it corresponds to the Command key. This may be a modifier.
Update 4 June 2023: keyboard monitor test program, to ensure Key.cmd
+ d
is correct for my keyboard (it is): modified from https://pynput.readthedocs.io/en/latest/keyboard.html#monitoring-the-keyboard:
from pynput import keyboard
print("Keyboard monitor demo program. Press Esc to exit.")
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
print("Exiting the program.")
return False
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
Sample output when I press Super + D:
$ ./pynput_monitor_keyboard.py
Keyboard monitor demo program. Press Esc to exit.
Key.enter released
special key Key.cmd pressed
alphanumeric key d pressed
'd' released
Key.cmd released