Search code examples
pythonstringencodingpyautogui

encoding of backslash in pythons pyautogui


I am trying write a python script that runs an external program automatically by clicking buttons and give keyboard input (usually file paths) with pyautogui. Now if I try use the funktion pyautogui.typewriter(filepath) it always types the backslashes as questionmarks. This minimal example:

pyautogui.typewrite('\\')

returns simply ?

Now, if I change my keyboard layout in the system settings to english, it correctly returns \

My default layout is german, and I cant really change that because this messes up the later stages of the program due to wrong date formats. Any ideas how to solve this problem?


Solution

  • Ok, I finally have a workaround, based on this discussion: https://github.com/asweigart/pyautogui/issues/46

    I tinkered around in _pyautogui_win.py. and changed the keyboard input for '\'. I got the virtual keycodes on my keyboard with this handy tool: http://www.delphiforfun.org/Programs/Utilities/KeyCodes.htm#Download and converted them to hex codes. I then changed the _keyDown function with the addition of this:

    if key == '\\': 
            ctypes.windll.user32.keybd_event(0x11, 0, 0, 0) # should be left control
            ctypes.windll.user32.keybd_event(0x12, 0, 0, 0) # should be alt
            ctypes.windll.user32.keybd_event(0xDB, 0, 0, 0) # should be alt ß
            ctypes.windll.user32.keybd_event(0x11, 0, KEYEVENTF_KEYUP, 0)
            ctypes.windll.user32.keybd_event(0x12, 0, KEYEVENTF_KEYUP, 0)
            ctypes.windll.user32.keybd_event(0xDB, 0, KEYEVENTF_KEYUP, 0)
            return
    

    Now everything works fine. I think this solution can be applied to any non-english keyboard layouts.