def press_key(keyString): isUpper = keyString.isupper() isSpecial = keyString in specialBindings if isSpecial: keyString = str(specialBindings[keyString]) if isSpecial or isUpper: key_down(16) key_down(char2keycode(keyString.lower())) key_up(char2keycode(keyString.lower())) if isSpecial or isUpper: key_up(16)
def SendKeys(keys, pause=0.05, with_spaces=False, with_tabs=False, with_newlines=False, turn_off_numlock=True): """ Sends keys to the current window. `keys` : str A string of keys. `pause` : float The number of seconds to wait between sending each key or key combination. `with_spaces` : bool Whether to treat spaces as ``{SPACE}``. If `False`, spaces are ignored. `with_tabs` : bool Whether to treat tabs as ``{TAB}``. If `False`, tabs are ignored. `with_newlines` : bool Whether to treat newlines as ``{ENTER}``. If `False`, newlines are ignored. `turn_off_numlock` : bool Whether to turn off `NUMLOCK` before sending keys. example:: SendKeys("+hello{SPACE}+world+1") would result in ``"Hello World!"`` """ restore_numlock = False try: # read keystroke keys into a list of 2 tuples [(key,up),] _keys = str2keys(keys, with_spaces, with_tabs, with_newlines) # certain keystrokes don't seem to behave the same way if NUMLOCK # is on (for example, ^+{LEFT}), so turn NUMLOCK off, if it's on # and restore its original state when done. if turn_off_numlock: restore_numlock = toggle_numlock(False) # "play" the keys to the active window playkeys(_keys, pause) finally: if restore_numlock and turn_off_numlock: key_down(CODES['NUMLOCK']) key_up(CODES['NUMLOCK'])
def playkeys(keys, pause=.05): """ Simulates pressing and releasing one or more keys. `keys` : str A list of 2-tuples consisting of ``(keycode,down)`` where `down` is `True` when the key is being pressed and `False` when it's being released. `keys` is returned from `str2keys`. `pause` : float Number of seconds between releasing a key and pressing the next one. """ for (vk, arg) in keys: if vk: if arg: key_down(vk) else: key_up(vk) if pause: # pause after key up time.sleep(pause) else: time.sleep(arg)