1

My goal is to display a tooltip wherever the user is typing. To do this, I need to find the location of the caret (the place where the user is typing). I'm using Windows 10 and Python 3.8. Based on this thread, I tried the following code:

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

The code prints 0,0 regardless of where the caret actually is. How can can I get the location of the caret on the screen?

Emily Conn
  • 126
  • 3
  • There is no supported way to use `AttachThreadInput` reliably from Python. Not much of a loss, since it's not part of your solution anyway. Use [WinEvents](https://learn.microsoft.com/en-us/windows/win32/winauto/winevents-infrastructure) instead. – IInspectable Aug 29 '20 at 10:37

1 Answers1

0

First of all, not all carets in the edit box cannot be read. GetCaretPos can only get the caret in the standard edit box.

So you can get caret in standard edit box like notepad, wordpad, etc., like this:

enter image description here

And now most of the edit boxes are not standard edit boxes, but rich text boxes. You can refer to EM_POSFROMCHAR to learn how to get the caret position in the rich text box, but the message is used in different ways depending on the version of the rich text box.

Parameters

wParam

Rich Edit 1.0 and 3.0: A pointer to a POINTL structure that receives the client area coordinates of the character. The coordinates are in screen units and are relative to the upper-left corner of the control's client area.

Edit controls and Rich Edit 2.0: The zero-based index of the character.

lParam

Rich Edit 1.0 and 3.0: The zero-based index of the character.

Edit controls and Rich Edit 2.0: This parameter is not used.

Return value

Rich Edit 1.0 and 3.0: The return value is not used.

Edit controls and Rich Edit 2.0: The return value contains the client area coordinates of the character. The LOWORD contains the horizontal coordinate and the HIWORD contains the vertical coordinate.

You can use GetClassName to get the classname, distinguish the version of richedit according to the classname, and send the message.

More references:About Rich Edit Controls, Get version of rich edit library

Zeus
  • 3,703
  • 3
  • 7
  • 20