方法一、
public Point GetPositionFromCharacterIndex(TextBox txtContent)
{
int lastIndex = txtContent.GetLastVisibleLineIndex();
int firstIndex = txtContent.GetFirstVisibleLineIndex();
int rowCount = lastIndex - firstIndex;
string lineVal = txtContent.GetLineText(lastIndex);
Typeface typeface = new Typeface(txtContent.FontFamily,
txtContent.FontStyle,
txtContent.FontWeight,
txtContent.FontStretch);
FormattedText formattedText = new FormattedText(lineVal,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface, txtContent.FontSize, txtContent.Background);
double X = 0d;
double Y = 0d;
if (lastIndex > 0)
{
X = formattedText.Width;
Y = rowCount * formattedText.Height > txtContent.ActualHeight ? (txtContent.ActualHeight - pp.Height - formattedText.Height) : ((rowCount - 1) * formattedText.Height - pp.Height);
}
else
{
X = formattedText.Width;
Y = -pp.Height;
}
Point point = new Point(X, Y);
return point;
}
方法二、
[DllImport("user32")]
public static extern bool GetCaretPos(out System.Drawing.Point lpPoint);