When you install a textbox SelectionStart (also when calculating a SelectionLength) using the GetCharacterIndexFromPoint function, you will never get a position beyond the last character (when trying to set the cursor to the end of the text). When specifying a point, after the text, this function returns the index of the last character, i.e. get the position BEFORE the last character. How to solve the code - what the user really wanted - set the cursor for or before the last character?
1 answer
This function will return the position to us depending on the location of the point of clicking the mouse on the textbox:
private int GetTxtCharIndex(TextBox txt, Point point) { int idx = txt.GetCharacterIndexFromPoint(point, true); if (txt.Text.Length > 0) { Rect rect = txt.GetRectFromCharacterIndex(idx); if (rect.Right < point.X) idx++; } return idx; }
|