Charles
Charles

Reputation: 7

Python key changer program

I have got a keyboard with a non-working windows key. I tried to fix it with Python if I press the > key, the program will press the windows key, but it's not working. Here's the code:

    import msvcrt
    import pyautogui
    while True:
        if msvcrt.kbhit():
            key_stroke = msvcrt.getch()
            if key_stroke == b'>':
                pyautogui.press('super')
                print(key_stroke)

Can anyone help me? Thanks

Upvotes: 1

Views: 2139

Answers (2)

Jevi
Jevi

Reputation: 89

If you want to remap keys in python, the keyboard module is what you are looking for.

Please install keyboard package first (pip install keyboard). Documentation

The remap_hotkey function does exactly what you need.

keyboard.wait blocks the execution of the code until a key is pressed.

import keyboard

keyboard.remap_hotkey("Shift+.", "windows")

while True:
    keyboard.wait()

Note that "Shift+." may change depending on your keyboard layout.

Upvotes: 1

deepak dash
deepak dash

Reputation: 245

To press ">" you need to press two keys "shift" + ".", when you release the "." key you registered ">" being a keystroke. but till that time you have not released the "shift" key.

In a nutshell when you execute pyautogui.press('super') in line 7, you are already pressing the "shift" key and then sending the "super" key command.

Solution to your problem is simple, release the "shift" key before sending the pyautogui.press('super') cmd.

The below code will resolve your problem.

Please install pynput package first (pip install pynput). Documentation for pynput

Solution - 1 (Modifying your code)

import msvcrt
import pyautogui
from pynput import keyboard

kb = keyboard.Controller()

while True:
    if msvcrt.kbhit():
        key_stroke = msvcrt.getch()
        if key_stroke == b'>':
            kb.release(keyboard.Key.shift)
            pyautogui.press('super')
            print(key_stroke)

Solution - 2 (This will give you more control over your keyboard events) To exit from the shell press the "Esc" key.

from pynput import keyboard

kb = keyboard.Controller()

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 hasattr(key, 'char') and key.char == ">":
        kb.release(keyboard.Key.shift)
        kb.press(keyboard.Key.cmd)
        kb.release(keyboard.Key.cmd)
    if key == keyboard.Key.esc:
        # Stop listener
        return False

# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

# ...or, in a non-blocking fashion:
listener = keyboard.Listener(
    on_press=on_press,
    on_release=on_release)
listener.start()

Upvotes: 0

Related Questions