WPF 获取当前文本光标所在窗口的坐标

来源:互联网 发布:产业链大数据包含 编辑:程序博客网 时间:2024/06/15 13:54

TextBox控件

 public Point GetPositionFromCharacterIndex()
        {

            int index = txtBox.CaretIndex;
            if (txtBox.TextWrapping == TextWrapping.Wrap) throw new NotSupportedException();

            var text = txtBox.Text.Substring(0, index);

            int lastNewLineIndex = text.LastIndexOf('\r');

            var leftText = lastNewLineIndex != -1 ? text.Substring(lastNewLineIndex + 1) : text;

            Typeface typeface = new Typeface(rich.FontFamily,
             txtBox.FontStyle,
             txtBox.FontWeight,
             txtBox.FontStretch);
            FormattedText formattedText = new FormattedText(leftText,
                CultureInfo.CurrentCulture,
                FlowDirection.LeftToRight,
                typeface, rich.FontSize, rich.Background);
            Point point = new Point(formattedText.Width, formattedText.Height);              //这里默认为第一行,如果多行,则formattedText.Height*n
            return point;
        }

 

RichTextBox

Rect r = rich.CaretPosition.GetCharacterRect(LogicalDirection.Forward);

 

 

原创粉丝点击