Skip to content

Instantly share code, notes, and snippets.

@xavieryin
Created November 24, 2021 06:22
Show Gist options
  • Save xavieryin/8bea8cc0dc9f080b2f1fb85834ebe130 to your computer and use it in GitHub Desktop.
Save xavieryin/8bea8cc0dc9f080b2f1fb85834ebe130 to your computer and use it in GitHub Desktop.

Revisions

  1. xavieryin created this gist Nov 24, 2021.
    28 changes: 28 additions & 0 deletions IME switch mode
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    from win32api import keybd_event, GetKeyboardLayout, GetKeyboardLayoutList, SendMessage
    from win32con import VK_LCONTROL, VK_SPACE, KEYEVENTF_KEYUP, WM_INPUTLANGCHANGEREQUEST
    from win32gui import GetForegroundWindow


    KEYBOARD_LAYOUT_EN = 0x04090409
    KEYBOARD_LAYOUT_TC = 0x04040404


    def switch_to_english():
    '''Typically Windows 10 is installed without English. But if it does, we can reliably switch easily.
    In normal cases only Traditional Chinese IME is installed with default setting. It defaults to
    Chinese mode and can be switch between English mode by Ctrl + Space.
    Here Ctrl + Space is blindly input since I can't find a better way.
    About virtual keys: https://docs.microsoft.com/zh-tw/windows/win32/inputdev/virtual-key-codes?redirectedfrom=MSDN
    '''
    if (current_keyboard_layout := GetKeyboardLayout()) != KEYBOARD_LAYOUT_EN:
    if KEYBOARD_LAYOUT_EN in GetKeyboardLayoutList():
    SendMessage(GetForegroundWindow(), WM_INPUTLANGCHANGEREQUEST, 0, KEYBOARD_LAYOUT_EN | 0xFFFF)
    else:
    # assert(current_keyboard_layout == KEYBOARD_LAYOUT_TC) # Traditional Chinese IME
    # Note that VK_SHIFT, VK_LSHIFT, VK_RSHIFT does not work
    # Ctrl + Space is one of the default switching methods
    keybd_event(VK_LCONTROL, 0, 0, 0)
    keybd_event(VK_SPACE, 0, 0, 0)
    keybd_event(VK_SPACE, 0, KEYEVENTF_KEYUP, 0)
    keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYUP, 0)