如何在RichTextbox中获取精确的光标位置以显示Popup

时间:2014-01-29 18:10:24

标签: wpf richtextbox cursor-position

我想在WPF中显示RichTextBox的POPUP特定位置。我知道有一种方法可以在winforms RichTextBox中使用以下代码行获得相同的内容。

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

2 个答案:

答案 0 :(得分:1)

我想这取决于你弹出的时间和内容。 MSDN中的一个示例显示了如何将ContextMenu与所选文本的位置放在RichTextBox控件中。 How to: Position a Custom Context Menu in a RichTextBox 有趣的是下面的代码:

TextPointer position = rtb.Selection.End;

if (position == null) return;

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

这将获得选择的相对位置。如果要弹出一个表单,则需要将其转换为Window位置。

这是我用来测试RichTextBox中所选文本的弹出窗口加载的一些代码。这也考虑了多个监视器。

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();

<强>更新 我做了一些额外的研究,发现了一篇MSDN Popup Placement Behavior文章,可能就Popup行为而言正在寻找。您可以使用我在上面提供的代码和RichTextBox的选择或插入位置来确定Popup的最终位置。我希望有所帮助。

答案 1 :(得分:0)

    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);}}}
相关问题