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 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()
If anybody is still running into this:
The copy doesn't work because the Alt key is still pressed from your global hotkey.
You can simply release the Alt key before triggering Ctrl+C:
keyboard.release(Key.alt)
keyboard.press(Key.ctrl)
keyboard.press('c')
keyboard.release('c')
keyboard.release(Key.ctrl)
This workaround is not required on Linux or macOS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With