moses-palmer / pynput

Sends virtual input commands
GNU Lesser General Public License v3.0
1.77k stars 245 forks source link

trying to combine pynput's globalhotkeys with pynput's keyboard controller - is this possible? #501

Open jb261 opened 1 year ago

jb261 commented 1 year ago

Global hotkeys working as expected:

from pynput import keyboard
import clipboard 
import pygetwindow as gw

def copy_clipboard():
    print(gw.getActiveWindowTitle())
    return clipboard.paste()

def function_1():
    print('Function 1 activated')
    clipboardContents = copy_clipboard()

def function_2():
    print('Function 2 activated')
    clipboardContents = copy_clipboard()

with keyboard.GlobalHotKeys({
        '<alt>+<shift>+u': function_1,
        '<ctrl>+<alt>+b': function_2}
        ) as h:
    h.join()

Keyboard controller working as expected:

from pynput import keyboard
import clipboard 
import time
import pygetwindow as gw

keybrd = keyboard.Controller()

time.sleep(3)  
print(gw.getActiveWindowTitle())
with keybrd.pressed(keyboard.Key.ctrl.value):
    keybrd.press('c')
    keybrd.release('c')

time.sleep(1)  
print(clipboard.paste())

But when I combine them, as in the following script, CTRL+c isn't being sent (or received by system, as selected text doesn't get copied into clipboard). I'm using pygetwindow just to confirm that the correct window has focus prior to sending CTRL+c.

from pynput import keyboard
import clipboard 
import pygetwindow as gw

keybrd = keyboard.Controller()

def copy_clipboard():
    print(gw.getActiveWindowTitle())
    with keybrd.pressed(keyboard.Key.ctrl.value):
        keybrd.press('c')
        keybrd.release('c')
    return clipboard.paste()

def function_1():
    print('Function 1 activated')
    clipboardContents = copy_clipboard()
    print(clipboardContents)

def function_2():
    print('Function 2 activated')
    clipboardContents = copy_clipboard()
    print(clipboardContents)

with keyboard.GlobalHotKeys({
        '<alt>+<shift>+u': function_1,
        '<ctrl>+<alt>+b': function_2}
        ) as h:
    h.join()

Is this a known limitation or is there something special I need to do to use both globalhotkeys and keyboard controller in the same script?