How is that a mistake? If you look at the description, it will get the closest character. , , . , , , .
, RichTextBox, , . -, , , : .
string originalText = richTextBox1.Text;
richTextBox1.Text += " ";
richTextBox1.Text = originalText;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectionStart = positionBegin;
, , , . , GetCharIndexFromPosition(Point pt), , , .
EDIT: ( )
RichTextBox, , :
public override int GetCharIndexFromPosition(Point pt) {
NativeMethods.POINT wpt = new NativeMethods.POINT(pt.X, pt.Y);
int index = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.EM_CHARFROMPOS, 0, wpt);
string t = this.Text;
if (index >= t.Length) {
index = Math.Max(t.Length - 1, 0);
}
return index;
}
"" , , , , , :
public static class RichTextBoxExtensions
{
private const int EM_CHARFROMPOS = 0x00D7;
public static int GetTrueIndexPositionFromPoint(this RichTextBox rtb, Point pt)
{
POINT wpt = new POINT(pt.X, pt.Y);
int index = (int)SendMessage(new HandleRef(rtb, rtb.Handle), EM_CHARFROMPOS, 0, wpt);
return index;
}
[DllImport("User32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, POINT lParam);
}
[StructLayout(LayoutKind.Sequential)]
internal class POINT
{
public int x;
public int y;
public POINT()
{
}
public POINT(int x, int y)
{
this.x = x;
this.y = y;
}
}
! GetCharIndexFromPosition GetTrueIndexPositionFromPoint .