开发者

How do I convert X y position within a TextBox to a text index?

I'm using a DragEventArgs for a Drop Ev开发者_运维问答ent and have the x, y Drop Insert position within a TextBox.

How do you convert the x, y to and Index within the TextField? I is extremely import for me to find out this inormation!

Thank you very much!


You need to use the GetCharacterIndexFromPoint method of the TextBox:

void textBox1_Drop(object sender, DragEventArgs e)
{
    TextBox textBox = (TextBox)sender;
    Point position = e.GetPosition(textBox);
    int index = textBox.GetCharacterIndexFromPoint(position, true);
    string text = (string)e.Data.GetData(typeof(string));
    textBox.SelectionStart = index;
    textBox.SelectionLength = 0;
    textBox.SelectedText = text;
}


Here is a small enhancement that calculates the position index of a character that is closest to the dropping point. The GetCharacterIndexFromPoint method actually does not return the position of the closest char (like it's documented), but it returns the index of the character that is under the dropped point (even if the dropped point is right next to the right edge of the char, in which case the method should return the index of the next char which is actually closer to the dropping point).

private int GetRoundedCharacterIndexFromPoint(TextBox textBox, Point dropPoint)
{
    int position = textBox.GetCharacterIndexFromPoint(dropPoint, true);

    // Check if the dropped point is actually closer to the next character
    // or if it exceeds the righmost character in the textbox
    // (in this case increase position by 1)
    Rect charLeftEdge = textBox.GetRectFromCharacterIndex(position, false);
    Rect charRightEdge = textBox.GetRectFromCharacterIndex(position, true);
    double charWidth = charRightEdge.X - charLeftEdge.X;
    if (dropPoint.X + charWidth / 2 > charRightEdge.X) position++;

    return position;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜