Python: Get caret position
Question: 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


Answer: If the caret is in a window created by another thread, you need to call
[`AttachThreadInput`](http://msdn.microsoft.com/en-
us/library/windows/desktop/ms681956%28v=vs.85%29.aspx). 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
    

