Detailed explanation of the method of realizing keyboard operation with python in automation

  • 2021-07-22 10:53:08
  • OfStack

Originally, press key method was used for keyboard operation in robotframework, but this method needs to write locator of the operated object, which is not very convenient. Now, a method for writing keyboard operation in win32api library has been found (note: the operation interface of this method must be at the top level). First, python library of win32api needs to be installed, and commands are used:


pip install pywin32

The specific implementation code is as follows:


import win32api
import win32con

class MyLibrary(object):
  def keybd_event(self,VK_CODE): #VK_CODE Encode the keyboard 
    # @Keyboard
    # input
    VK_CODE = int(VK_CODE)
    print ":::VK_CODE:", VK_CODE
    win32api.keybd_event(VK_CODE, 0, 0, 0)
    win32api.keybd_event(VK_CODE, 0, win32con.KEYEVENTF_KEYUP, 0)
    print ":::press", str(VK_CODE), "successfully!"
    time.sleep(2)

if __name__ == '__main__':
    keybd_event(40) # Keyboard press direction down key 

Common keyboard codes: (from Baidu)

ESC Bond VK_ESCAPE (27)
Enter key: VK_RETURN (13)
TAB key: VK_TAB (9)
Caps Lock Key: VK_CAPITAL (20)
Shift key: VK_SHIFT (16)
Ctrl key: VK_CONTROL (17)
Alt key: VK_MENU (18)
Spacebar: VK_SPACE (32)
Backspace key: VK_BACK (8)
Left logo key: VK_LWIN (91)
Right logo key: VK_RWIN (92)
Right mouse button shortcut: VK_APPS (93)
Insert key: VK_INSERT (45)
Home key: VK_HOME (36)
Page Up: VK_PRIOR (33)
PageDown: VK_NEXT (34)
End key: VK_END (35)
Delete key: VK_DELETE (46)
Arrow keys (→): VK_LEFT (37)
Arrow keys (↑): VK_UP (38)
Arrow keys (→): VK_RIGHT (39)
Arrow keys (left): VK_DOWN (40)
F1 Key: VK_F1 (112)
F2 Key: VK_F2 (113)
F3 Key: VK_F3 (114)
F4 Key: VK_F4 (115)
F5 Key: VK_F5 (116)
F6 Key: VK_F6 (117)
F7 Key: VK_F7 (118)
F8 Key: VK_F8 (119)
F9 Key: VK_F9 (120)
F10 Key: VK_F10 (121)
F11 Key: VK_F11 (122)
F12 Key: VK_F12 (123)
Num Lock Key: VK_NUMLOCK (144)
Keypad 0: VK_NUMPAD0 (96)
Keyboard 1: VK_NUMPAD1 (97)
Keyboard 2: VK_NUMPAD2 (98)
Keyboard 3: VK_NUMPAD3 (99)
Keyboard 4: VK_NUMPAD4 (100)
Keyboard 5: VK_NUMPAD5 (101)
Keypad 6: VK_NUMPAD6 (102)
Keypad 7: VK_NUMPAD7 (103)
Keypad 8: VK_NUMPAD8 (104)
Keyboard 9: VK_NUMPAD9 (105)
Keyboard. : VK_DECIMAL (110)
Keypad *: VK_MULTIPLY (106)
Keyboard +: VK_ADD (107)
Keypad-: VK_SUBTRACT (109)
Keypad/: VK_DIVIDE (111)
Pause Break Key: VK_PAUSE (19)
Scroll Lock Key: VK_SCROLL (145)


Related articles: