Search code examples
pythonpositionpywin32caret

Python: Get caret position


I'm trying to get the caret position in Python. I tried using win32gui.GetCaretPos() but it always returns 0,0.

Do you have any ideas how to make it work?

Thanks Chris


Solution

  • If the caret is in a window created by another thread, you need to call AttachThreadInput. Assuming you want the caret of the foreground window, you can get to it like this:

    import win32gui
    import win32process
    import win32api
    
    fg_win = win32gui.GetForegroundWindow()
    fg_thread, fg_process = win32process.GetWindowThreadProcessId(fg_win)
    current_thread = win32api.GetCurrentThreadId()
    win32process.AttachThreadInput(current_thread, fg_thread, True)
    try:
        print win32gui.GetCaretPos()
    finally:
        win32process.AttachThreadInput(current_thread, fg_thread, False) #detach