I am trying to enter Alt-codes of symbols using the pynput library (Imitation of pressing "Alt" and entering code on the numpad)
from pynput.keyboard import Key, Controller
keyb = Controller()
def alt_codes(start, finish):
for i in range(start, finish + 1):
keyb.press(Key.alt)
time.sleep(0.01)
for j in str(i):
keyb.press(j)
time.sleep(0.01)
keyb.release(j)
time.sleep(0.01)
keyb.release(Key.alt)
time.sleep(0.01)
keyb.press(Key.space)
time.sleep(0.01)
keyb.release(Key.space)
But if I just try to simulate pressing the numbers 0 to 9, it doesn't work, because it simulates pressing the keys that are above the letters, and to enter the Alt code, you need to simulate the numbers from the Numpad. How can I simulate pressing numbers on a numpad? UPD: You can use any other library if needed.
For specifically targeting the Numpad keys you can use their Virtual-Key Codes
You can find the whole list here https://cherrytree.at/misc/vk.htm
Now for the Code to Use the Virtual Key Codes
keyb.press(key=KeyCode.from_vk(96)) #Number tells which numpad key to press, 96 means 0
instead of
keyb.press(j)
You can change the start to finish instead of 0 to 9
to
96 to 105
. In this way, you can press the specific key subsequently
Or you can define a mapping for it like this:
get_keycode = {
0: 96,
1: 97,
2: 98,
3: 99,
4: 100,
5: 101,
6: 102,
7: 103,
8: 104,
9: 105
}
Now your final code would be (I tried writing Euro Sign ALT-Code is 0128):
from pynput.keyboard import Key, Controller, KeyCode
import time
keyb = Controller()
get_keycode = {
0: 96,
1: 97,
2: 98,
3: 99,
4: 100,
5: 101,
6: 102,
7: 103,
8: 104,
9: 105
}
def get_key(key):
return KeyCode.from_vk(get_keycode[int(key)])
euro_sign = "0128"
keyb.press(Key.alt)
time.sleep(0.01)
for j in euro_sign:
keyb.press(get_key(j))
time.sleep(0.01)
keyb.release(get_key(j))
time.sleep(0.01)
keyb.release(Key.alt)
time.sleep(0.01)
keyb.press(Key.space)
time.sleep(0.01)
keyb.release(Key.space)
Hope this helps!