Python模拟按键

Python模拟按键,第1张

Python模拟按键

代码应使您入门。

ctypes
被大量使用。在底部,您将看到示例代码。

import ctypesLONG = ctypes.c_longDWORD = ctypes.c_ulongULONG_PTR = ctypes.POINTER(DWORD)WORD = ctypes.c_ushortclass MOUSEINPUT(ctypes.Structure):    _fields_ = (('dx', LONG),     ('dy', LONG),     ('mouseData', DWORD),     ('dwFlags', DWORD),     ('time', DWORD),     ('dwExtraInfo', ULONG_PTR))class KEYBDINPUT(ctypes.Structure):    _fields_ = (('wVk', WORD),     ('wScan', WORD),     ('dwFlags', DWORD),     ('time', DWORD),     ('dwExtraInfo', ULONG_PTR))class HARDWAREINPUT(ctypes.Structure):    _fields_ = (('uMsg', DWORD),     ('wParamL', WORD),     ('wParamH', WORD))class _INPUTunion(ctypes.Union):    _fields_ = (('mi', MOUSEINPUT),     ('ki', KEYBDINPUT),     ('hi', HARDWAREINPUT))class INPUT(ctypes.Structure):    _fields_ = (('type', DWORD),     ('union', _INPUTunion))def SendInput(*inputs):    nInputs = len(inputs)    LPINPUT = INPUT * nInputs    pInputs = LPINPUT(*inputs)    cbSize = ctypes.c_int(ctypes.sizeof(INPUT))    return ctypes.windll.user32.SendInput(nInputs, pInputs, cbSize)INPUT_MOUSE = 0INPUT_KEYBOARD = 1INPUT_HARDWARD = 2def Input(structure):    if isinstance(structure, MOUSEINPUT):        return INPUT(INPUT_MOUSE, _INPUTunion(mi=structure))    if isinstance(structure, KEYBDINPUT):        return INPUT(INPUT_KEYBOARD, _INPUTunion(ki=structure))    if isinstance(structure, HARDWAREINPUT):        return INPUT(INPUT_HARDWARE, _INPUTunion(hi=structure))    raise TypeError('Cannot create INPUT structure!')WHEEL_DELTA = 120XBUTTON1 = 0x0001XBUTTON2 = 0x0002MOUSEEVENTF_ABSOLUTE = 0x8000MOUSEEVENTF_HWHEEL = 0x01000MOUSEEVENTF_MOVE = 0x0001MOUSEEVENTF_MOVE_NOCOALESCE = 0x2000MOUSEEVENTF_LEFTDOWN = 0x0002MOUSEEVENTF_LEFTUP = 0x0004MOUSEEVENTF_RIGHTDOWN = 0x0008MOUSEEVENTF_RIGHTUP = 0x0010MOUSEEVENTF_MIDDLEDOWN = 0x0020MOUSEEVENTF_MIDDLEUP = 0x0040MOUSEEVENTF_VIRTUALDESK = 0x4000MOUSEEVENTF_WHEEL = 0x0800MOUSEEVENTF_XDOWN = 0x0080MOUSEEVENTF_XUP = 0x0100def MouseInput(flags, x, y, data):    return MOUSEINPUT(x, y, data, flags, 0, None)VK_LBUTTON = 0x01    # Left mouse buttonVK_RBUTTON = 0x02    # Right mouse buttonVK_CANCEL = 0x03     # Control-break processingVK_MBUTTON = 0x04    # Middle mouse button (three-button mouse)VK_XBUTTON1 = 0x05   # X1 mouse buttonVK_XBUTTON2 = 0x06   # X2 mouse buttonVK_BACK = 0x08       # BACKSPACE keyVK_TAB = 0x09        # TAB keyVK_CLEAR = 0x0C      # CLEAR keyVK_RETURN = 0x0D     # ENTER keyVK_SHIFT = 0x10      # SHIFT keyVK_ConTROL = 0x11    # CTRL keyVK_MENU = 0x12       # ALT keyVK_PAUSE = 0x13      # PAUSE keyVK_CAPITAL = 0x14    # CAPS LOCK keyVK_KANA = 0x15       # IME Kana modeVK_HANGUL = 0x15     # IME Hangul modeVK_JUNJA = 0x17      # IME Junja modeVK_FINAL = 0x18      # IME final modeVK_HANJA = 0x19      # IME Hanja modeVK_KANJI = 0x19      # IME Kanji modeVK_ESCAPE = 0x1B     # ESC keyVK_ConVERT = 0x1C    # IME convertVK_NonCONVERT = 0x1D # IME nonconvertVK_ACCEPT = 0x1E     # IME acceptVK_MODECHANGE = 0x1F # IME mode change requestVK_SPACE = 0x20      # SPACEBARVK_PRIOR = 0x21      # PAGE UP keyVK_NEXT = 0x22       # PAGE DOWN keyVK_END = 0x23        # END keyVK_HOME = 0x24       # HOME keyVK_LEFT = 0x25       # LEFT ARROW keyVK_UP = 0x26         # UP ARROW keyVK_RIGHT = 0x27      # RIGHT ARROW keyVK_DOWN = 0x28       # DOWN ARROW keyVK_SELECT = 0x29     # SELECT keyVK_PRINT = 0x2A      # PRINT keyVK_EXECUTE = 0x2B    # EXECUTE keyVK_SNAPSHOT = 0x2C   # PRINT SCREEN keyVK_INSERT = 0x2D     # INS keyVK_DELETE = 0x2E     # DEL keyVK_HELP = 0x2F       # HELP keyVK_LWIN = 0x5B       # Left Windows key (Natural keyboard)VK_RWIN = 0x5C       # Right Windows key (Natural keyboard)VK_APPS = 0x5D       # Applications key (Natural keyboard)VK_SLEEP = 0x5F      # Computer Sleep keyVK_NUMPAD0 = 0x60    # Numeric keypad 0 keyVK_NUMPAD1 = 0x61    # Numeric keypad 1 keyVK_NUMPAD2 = 0x62    # Numeric keypad 2 keyVK_NUMPAD3 = 0x63    # Numeric keypad 3 keyVK_NUMPAD4 = 0x64    # Numeric keypad 4 keyVK_NUMPAD5 = 0x65    # Numeric keypad 5 keyVK_NUMPAD6 = 0x66    # Numeric keypad 6 keyVK_NUMPAD7 = 0x67    # Numeric keypad 7 keyVK_NUMPAD8 = 0x68    # Numeric keypad 8 keyVK_NUMPAD9 = 0x69    # Numeric keypad 9 keyVK_MULTIPLY = 0x6A   # Multiply keyVK_ADD = 0x6B        # Add keyVK_SEPARATOR = 0x6C  # Separator keyVK_SUBTRACT = 0x6D   # Subtract keyVK_DECIMAL = 0x6E    # Decimal keyVK_DIVIDE = 0x6F     # Divide keyVK_F1 = 0x70         # F1 keyVK_F2 = 0x71         # F2 keyVK_F3 = 0x72         # F3 keyVK_F4 = 0x73         # F4 keyVK_F5 = 0x74         # F5 keyVK_F6 = 0x75         # F6 keyVK_F7 = 0x76         # F7 keyVK_F8 = 0x77         # F8 keyVK_F9 = 0x78         # F9 keyVK_F10 = 0x79        # F10 keyVK_F11 = 0x7A        # F11 keyVK_F12 = 0x7B        # F12 keyVK_F13 = 0x7C        # F13 keyVK_F14 = 0x7D        # F14 keyVK_F15 = 0x7E        # F15 keyVK_F16 = 0x7F        # F16 keyVK_F17 = 0x80        # F17 keyVK_F18 = 0x81        # F18 keyVK_F19 = 0x82        # F19 keyVK_F20 = 0x83        # F20 keyVK_F21 = 0x84        # F21 keyVK_F22 = 0x85        # F22 keyVK_F23 = 0x86        # F23 keyVK_F24 = 0x87        # F24 keyVK_NUMLOCK = 0x90    # NUM LOCK keyVK_SCROLL = 0x91     # SCROLL LOCK keyVK_LSHIFT = 0xA0     # Left SHIFT keyVK_RSHIFT = 0xA1     # Right SHIFT keyVK_LConTROL = 0xA2   # Left ConTROL keyVK_RConTROL = 0xA3   # Right ConTROL keyVK_LMENU = 0xA4      # Left MENU keyVK_RMENU = 0xA5      # Right MENU keyVK_BROWSER_BACK = 0xA6          # Browser Back keyVK_BROWSER_FORWARD = 0xA7       # Browser Forward keyVK_BROWSER_REFRESH = 0xA8       # Browser Refresh keyVK_BROWSER_STOP = 0xA9          # Browser Stop keyVK_BROWSER_SEARCH = 0xAA        # Browser Search keyVK_BROWSER_FAVORITES = 0xAB     # Browser Favorites keyVK_BROWSER_HOME = 0xAC          # Browser Start and Home keyVK_VOLUME_MUTE = 0xAD# Volume Mute keyVK_VOLUME_DOWN = 0xAE# Volume Down keyVK_VOLUME_UP = 0xAF  # Volume Up keyVK_MEDIA_NEXT_TRACK = 0xB0      # Next Track keyVK_MEDIA_PREV_TRACK = 0xB1      # Previous Track keyVK_MEDIA_STOP = 0xB2 # Stop Media keyVK_MEDIA_PLAY_PAUSE = 0xB3      # Play/Pause Media keyVK_LAUNCH_MAIL = 0xB4# Start Mail keyVK_LAUNCH_MEDIA_SELECT = 0xB5   # Select Media keyVK_LAUNCH_APP1 = 0xB6# Start Application 1 keyVK_LAUNCH_APP2 = 0xB7# Start Application 2 keyVK_OEM_1 = 0xBA      # Used for miscellaneous characters; it can vary by keyboard.          # For the US standard keyboard, the ';:' keyVK_OEM_PLUS = 0xBB   # For any country/region, the '+' keyVK_OEM_COMMA = 0xBC  # For any country/region, the ',' keyVK_OEM_MINUS = 0xBD  # For any country/region, the '-' keyVK_OEM_PERIOD = 0xBE # For any country/region, the '.' keyVK_OEM_2 = 0xBF      # Used for miscellaneous characters; it can vary by keyboard.          # For the US standard keyboard, the '/?' keyVK_OEM_3 = 0xC0      # Used for miscellaneous characters; it can vary by keyboard.          # For the US standard keyboard, the '`~' keyVK_OEM_4 = 0xDB      # Used for miscellaneous characters; it can vary by keyboard.          # For the US standard keyboard, the '[{' keyVK_OEM_5 = 0xDC      # Used for miscellaneous characters; it can vary by keyboard.          # For the US standard keyboard, the '|' keyVK_OEM_6 = 0xDD      # Used for miscellaneous characters; it can vary by keyboard.          # For the US standard keyboard, the ']}' keyVK_OEM_7 = 0xDE      # Used for miscellaneous characters; it can vary by keyboard.          # For the US standard keyboard, the 'single-quote/double-quote' keyVK_OEM_8 = 0xDF      # Used for miscellaneous characters; it can vary by keyboard.VK_OEM_102 = 0xE2    # Either the angle bracket key or the backslash key on the RT 102-key keyboardVK_PROCESSKEY = 0xE5 # IME PROCESS keyVK_PACKET = 0xE7     # Used to pass Unipre characters as if they were keystrokes. The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT, SendInput, WM_KEYDOWN, and WM_KEYUPVK_ATTN = 0xF6       # Attn keyVK_CRSEL = 0xF7      # CrSel keyVK_EXSEL = 0xF8      # ExSel keyVK_EREOF = 0xF9      # Erase EOF keyVK_PLAY = 0xFA       # Play keyVK_ZOOM = 0xFB       # Zoom keyVK_PA1 = 0xFD        # PA1 keyVK_OEM_CLEAR = 0xFE  # Clear keyKEYEVENTF_EXTENDEDKEY = 0x0001KEYEVENTF_KEYUP = 0x0002KEYEVENTF_SCANCODE = 0x0008KEYEVENTF_UNICODE = 0x0004KEY_0 = 0x30KEY_1 = 0x31KEY_2 = 0x32KEY_3 = 0x33KEY_4 = 0x34KEY_5 = 0x35KEY_6 = 0x36KEY_7 = 0x37KEY_8 = 0x38KEY_9 = 0x39KEY_A = 0x41KEY_B = 0x42KEY_C = 0x43KEY_D = 0x44KEY_E = 0x45KEY_F = 0x46KEY_G = 0x47KEY_H = 0x48KEY_I = 0x49KEY_J = 0x4AKEY_K = 0x4BKEY_L = 0x4CKEY_M = 0x4DKEY_N = 0x4EKEY_O = 0x4FKEY_P = 0x50KEY_Q = 0x51KEY_R = 0x52KEY_S = 0x53KEY_T = 0x54KEY_U = 0x55KEY_V = 0x56KEY_W = 0x57KEY_X = 0x58KEY_Y = 0x59KEY_Z = 0x5Adef KeybdInput(pre, flags):    return KEYBDINPUT(pre, pre, flags, 0, None)def HardwareInput(message, parameter):    return HARDWAREINPUT(message & 0xFFFFFFFF,   parameter & 0xFFFF,   parameter >> 16 & 0xFFFF)def Mouse(flags, x=0, y=0, data=0):    return Input(MouseInput(flags, x, y, data))def Keyboard(pre, flags=0):    return Input(KeybdInput(pre, flags))def Hardware(message, parameter=0):    return Input(HardwareInput(message, parameter))################################################################################import stringUPPER = frozenset('~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?')LOWER = frozenset("`1234567890-=qwertyuiop[]\asdfghjkl;'zxcvbnm,./")ORDER = string.ascii_letters + string.digits + ' brt'ALTER = dict(zip('!@#$%^&*()', '1234567890'))OTHER = {'`': VK_OEM_3,         '~': VK_OEM_3,         '-': VK_OEM_MINUS,         '_': VK_OEM_MINUS,         '=': VK_OEM_PLUS,         '+': VK_OEM_PLUS,         '[': VK_OEM_4,         '{': VK_OEM_4,         ']': VK_OEM_6,         '}': VK_OEM_6,         '\': VK_OEM_5,         '|': VK_OEM_5,         ';': VK_OEM_1,         ':': VK_OEM_1,         "'": VK_OEM_7,         '"': VK_OEM_7,         ',': VK_OEM_COMMA,         '<': VK_OEM_COMMA,         '.': VK_OEM_PERIOD,         '>': VK_OEM_PERIOD,         '/': VK_OEM_2,         '?': VK_OEM_2}def keyboard_stream(string):    mode = False    for character in string.replace('rn', 'r').replace('n', 'r'):        if mode and character in LOWER or not mode and character in UPPER: yield Keyboard(VK_SHIFT, mode and KEYEVENTF_KEYUP) mode = not mode        character = ALTER.get(character, character)        if character in ORDER: pre = ord(character.upper())        elif character in OTHER: pre = OTHER[character]        else: continue raise ValueError('String is not understood!')        yield Keyboard(pre)        yield Keyboard(pre, KEYEVENTF_KEYUP)    if mode:        yield Keyboard(VK_SHIFT, KEYEVENTF_KEYUP)################################################################################import time, sysdef main():    time.sleep(5)    for event in keyboard_stream('o2E^uXh#:SHn&HQ+t]YF'):        SendInput(event)        time.sleep(0.1)##if __name__ == '__main__':##    main()def switch_program():    SendInput(Keyboard(VK_MENU), Keyboard(VK_TAB))    time.sleep(0.2)    SendInput(Keyboard(VK_TAB, KEYEVENTF_KEYUP),   Keyboard(VK_MENU, KEYEVENTF_KEYUP))    time.sleep(0.2)def select_line():    SendInput(Keyboard(VK_SHIFT, KEYEVENTF_EXTENDEDKEY),   Keyboard(VK_END, KEYEVENTF_EXTENDEDKEY))    time.sleep(0.2)    SendInput(Keyboard(VK_SHIFT, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP),   Keyboard(VK_END, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP))    time.sleep(0.2)def copy_line():    SendInput(Keyboard(VK_CONTROL), Keyboard(KEY_C))    time.sleep(0.2)    SendInput(Keyboard(VK_CONTROL, KEYEVENTF_KEYUP),   Keyboard(KEY_C, KEYEVENTF_KEYUP))    time.sleep(0.2)def next_line():    SendInput(Keyboard(VK_HOME), Keyboard(VK_DOWN))    time.sleep(0.2)    SendInput(Keyboard(VK_HOME, KEYEVENTF_KEYUP),   Keyboard(VK_DOWN, KEYEVENTF_KEYUP))    time.sleep(0.2)def prepare_text():    # Open Text    SendInput(Keyboard(KEY_M))    time.sleep(0.2)    SendInput(Keyboard(KEY_M, KEYEVENTF_KEYUP))    time.sleep(0.2)    # Goto Area    SendInput(Keyboard(VK_TAB))    time.sleep(0.2)    SendInput(Keyboard(VK_TAB, KEYEVENTF_KEYUP))    time.sleep(0.2)    # Paste Message    SendInput(Keyboard(VK_CONTROL), Keyboard(KEY_V))    time.sleep(0.2)    SendInput(Keyboard(VK_CONTROL, KEYEVENTF_KEYUP),   Keyboard(KEY_V, KEYEVENTF_KEYUP))    time.sleep(0.2)    # Goto Button    SendInput(Keyboard(VK_TAB))    time.sleep(0.2)    SendInput(Keyboard(VK_TAB, KEYEVENTF_KEYUP))    time.sleep(0.2)def send_one_message():    select_line()    copy_line()    next_line()    switch_program()    prepare_text()    # Send Message    SendInput(Keyboard(VK_RETURN))    time.sleep(0.2)    SendInput(Keyboard(VK_RETURN, KEYEVENTF_KEYUP))    time.sleep(10)    switch_program()def send_messages(total):    time.sleep(10)    for _ in range(total):        send_one_message()


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5654637.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存