[tkinter][Windows]Unexpected state report for the tab key

Eryk Sun eryksun at gmail.com
Mon Oct 25 02:48:22 EDT 2021


On 10/24/21, Stefan Ram <ram at zedat.fu-berlin.de> wrote:
> ram at zedat.fu-berlin.de (Stefan Ram) writes:
>>tab_down_hllDll.GetKeyState(tab_down_VK_TAB) & 0b1000000000000000
>
>   In the meantime, I read about "GetAsyncKeyState". I thought that
>   this would solve my problem, but no.

Odd. It works for me in the classic console and the Windows Terminal
pseudoconsole. The tab key's up/down state is updated immediately.

    import ctypes
    import msvcrt
    import time

    kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
    user32 = ctypes.WinDLL('user32', use_last_error=True)

    VK_TAB = 0x09

    def tab_down():
        return bool(user32.GetAsyncKeyState(VK_TAB) & 0x8000)

    def flush_console_input():
        """Flush the input buffer of the process (pseudo)console."""
        try:
            with open('conin$') as f:
                h = msvcrt.get_osfhandle(f.fileno())
                kernel32.FlushConsoleInputBuffer(h)
        except OSError:
            pass

    def test():
        for i in range(100):
            print('tab down:', tab_down())
            time.sleep(0.1)
        flush_console_input()

    test()

Flushing the console input buffer isn't necessary. I just prefer it
instead of leaving the key presses in the buffer.

Usually a GUI wants GetKeyState() instead, which is synchronized with
input messages in the thread's message queue as they're processed. But
GetAsyncKeyState() should do what you want, if you don't need
synchronization with input messages.


More information about the Python-list mailing list