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

匿名 (未验证) 提交于 2019-12-03 01:27:01

问题:

I'm using a DragEventArgs for a Drop Event 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!

回答1:

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; } 


回答2:

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; } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!