pynput
pynput copied to clipboard
[help requirement] pynput does not send ctrl+c to copy selected text
I am using python 2.7 on win7 64 bits. Here is a code, which just replaces every selected text by <h1>text</h1>. pynput-1.6.8 is used for global hotkey and keypress, while pyperclip-1.7.0 is used to handle clipboard.
But I found that in fact, ctrl+c is not pressed at all.
What is the problem? Thanks
from pynput.keyboard import Key, Controller, GlobalHotKeys
import pyperclip
# initilize the clipboard to null
pyperclip.copy('')
keyboard = Controller()
def on_activate_h():
print('<ctrl>+<alt>+h pressed')
# copy current text to clipboard
# but in fact, it does not work on my PC
# why??
keyboard.press(Key.ctrl)
keyboard.press('c')
keyboard.release('c')
keyboard.release(Key.ctrl)
txt = pyperclip.paste()
if txt:
keyboard.type(f'<h1>{txt}</h1>')
def on_activate_i():
print('<ctrl>+<alt>+i pressed')
with GlobalHotKeys({
'<ctrl>+<alt>+h': on_activate_h,
'<ctrl>+<alt>+i': on_activate_i}) as h:
h.join()
When on_activate_h evaluate, <alt> not released, so system actual got <ctrl>+<alt>+c.
solution:
def on_activate_h():
# ...........
keyboard.release(Key.alt)
with keyboard.pressed(Key.ctrl):
keyboard.press('c')
keyboard.release('c')
# ................