asweigart / pyautogui

A cross-platform GUI automation Python module for human beings. Used to programmatically control the mouse & keyboard.
BSD 3-Clause "New" or "Revised" License
10.22k stars 1.24k forks source link

proposition concering shift typing on mac #692

Open 278Mt opened 2 years ago

278Mt commented 2 years ago

I propose to rewrite such my code concerning shift typing on mac.

def _normalKeyEvent(key, upDown):
    assert upDown in ('up', 'down'), "upDown argument must be 'up' or 'down'"

    try:
        if pyautogui.isShiftCharacter(key):
            key_code = keyboardMapping[key.lower()]

            event = Quartz.CGEventCreateKeyboardEvent(None,
                        keyboardMapping['shift'], upDown == 'down')
            # 278Mt's comment: It is better to type with shift key with CGEventSetFlags() function.
            # reference is:
            # [here](https://stackoverflow.com/questions/55120977/how-press-shift-command-3-simultaneously-programmatically)
            # and [here](https://code-examples.net/en/q/1ea43e),
            # NOT [here](https://developer.apple.com/documentation/coregraphics/1456564-cgeventcreatekeyboardevent)
            Quartz.CGEventSetFlags(event, Quartz.kCGEventFlagMaskShift)

        else:
            key_code = keyboardMapping[key]

        event = Quartz.CGEventCreateKeyboardEvent(None, key_code, upDown == 'down')
        Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)
        time.sleep(pyautogui.DARWIN_CATCH_UP_TIME)

    # TODO - wait, is the shift key's keyup not done?
    # TODO - get rid of this try-except.

    except KeyError:
        raise RuntimeError("Key %s not implemented." % (key))

I've translated Swift into Python on here and here, NOT here