1

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

treddy
  • 2,771
  • 2
  • 18
  • 31
Chris Hki
  • 137
  • 1
  • 1
  • 6

1 Answers1

0

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
Janne Karila
  • 24,266
  • 6
  • 53
  • 94