I've got a subclassed text box that acquires keyboard focus (caret) only if the user intentionally clicks into it (it's part of a complex control where the user may not always want such behavior).
Accordingly, I have to give the text box this focus in code (with Keyboard.Focus), so I cannot rely on existing behavior to do it.
The problem is that when the user clicks in (and I invoke Keyboard.Focus), the caret position is not set. This is not intuitive, and mildly frustrating, necessitating a second click action from the user (once keyboard focus is acquired) to place the caret in the correct spot they wanted.
I would use GetCharacterIndexFromPoint, but it gives you the wrong index! If your mouse is beyond the last character, it will place the caret before it when clicked, which is arguably more irritating than no behavior at all in my opinion.
To this end, how can I take the mouse position and derive a suitable caret location from it, in a manner that mimics the out of the box behavior of the control (caret jumps to nearest valid position to mouse)?
I've researched this previously and came up blank.