user5979
user5979

Reputation: 121

How to get exact cursor position in RichTextbox to display Popup

I Want to display POPUP specific position of RichTextBox in WPF . i have understood that there is a way to get the same in winforms RichTextBox with following lines of code.

Point point = richTextBox1.GetPositionFromCharIndex(richTextBox1.SelectionStart);

Upvotes: 2

Views: 2990

Answers (2)

Phillip Gunnell
Phillip Gunnell

Reputation: 1

static void tb_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{ 
    if (e.KeyStates == ((e.KeyStates ^ System.Windows.Input.KeyStates.Down)^System.Windows.Input.KeyStates.Down))
    {
        if (e.Key == System.Windows.Input.Key.OemPeriod)
        {
            TextBox tb = (TextBox)sender;
           
            Rect r = tb.GetRectFromCharacterIndex(tb.CaretIndex, true);
            Point p = tb.TransformToAncestor(tb).Transform(new Point(r.X, r.Y + 10));
            p = tb.PointToScreen(p);
       
            Rect rect = new Rect(p.X, p.Y, 0, 0);
            Grid g = (Grid)Application.Current.MainWindow.Content;
            System.Windows.Controls.Primitives.Popup popup = new System.Windows.Controls.Primitives.Popup();
            popup.SetValue(System.Windows.Controls.Primitives.Popup.PlacementRectangleProperty, rect);
              
            popup.IsOpen = true;
            g.Children.Add(popup);
        }
    }
}

Upvotes: 0

Ward
Ward

Reputation: 116

I suppose it depends on when and what you are popping up. An example from MSDN shows how to position a ContextMenu with the location of the selected text within a RichTextBox control. How to: Position a Custom Context Menu in a RichTextBox The interesting bit would be the code below:

TextPointer position = rtb.Selection.End;

if (position == null) return;

Rect positionRect = position.GetCharacterRect(LogicalDirection.Forward);
contextMenu.HorizontalOffset = positionRect.X;
contextMenu.VerticalOffset = positionRect.Y;

This gets the relative position of the selection. If you are popping up a form you will need to translate that into a Window position.

This is a bit of code I used to test loading a popup window over the selected text in a RichTextBox. This also takes into account multiple monitors.

TextPointer tp = txtEditor.Selection.End;
if (tp == null) return;
Rect charRect = tp.GetCharacterRect(LogicalDirection.Forward);
Point winPoint = txtEditor.PointToScreen(charRect.TopRight);
Popup p = new Popup();
p.Left = winPoint.X;
p.Top = winPoint.Y;
p.Show();

UPDATE: I did some additional research and found a MSDN Popup Placement Behavior article that is likely what you are looking for as far as Popup behavior. You can use the code I provided above with the selection or caret position of the RichTextBox to then determine the ultimate positioning of the Popup. I hope that helps.

Upvotes: 1

Related Questions