SelectionStart 在反向選取時回傳錯誤值。正確做法呼叫 Win32 API GetCaretPos 取得螢幕座標,再轉換為字元索引。
using System.Runtime.InteropServices;
using System.Drawing;
using System.Windows.Forms;
public partial class Form1 : Form
{
[DllImport("user32.dll")]
private static extern bool GetCaretPos(out Point ppt);
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
Point p;
GetCaretPos(out p);
int index = this.textBox1.GetCharIndexFromPosition(p);
this.Text = index.ToString();
}
}
關鍵:GetCaretPos 取得插入點螢幕座標,GetCharIndexFromPosition 轉為控件內字元索引。