tags:

views:

446

answers:

3

I need to know the position of the caret in a TextBox so I can pop up a context menu near it. How do I find its placement (not character index)?

+1  A: 

Check out this example.

JP Alioto
I want to pop up the context menu near the caret as the user types (kind of like intellisense), not simply replace the default context menu.
RandomEngy
A: 

I think you will have to get the character index of the carat and then turn that into a pixel coordinate by calling TextRenderer.MeasureText() on the text to the left of the carat. This is obviously more complicated if your TextBox is multiline. Is it?

Fantius
It's single line, fortunately. I'll give the measuring text thing a shot.
RandomEngy
TextRenderer.MeasureText() appears to be for WinForms, not WPF. I found the equivalent for WPF, but I'm having difficulty grabbing the position of the TextBox I need to calculate the anchor point for the context menu.
RandomEngy
Oh, WPF. Even though you used the WPF tag, you should probably also have that kind of information in the question.
Fantius
+1  A: 

Found this article describing how to do what I need done. Turns out you can set both the PlacementTarget of the textbox and the PlacementRectangle from GetRectFromCharacterIndex and it will work.

RandomEngy