C# tips- 设置文本框光标的位置

问题:

希望设置TextBox 中的光标到任意位置。

设置SelectStart 和Length 不一地起作用,并不希望选中文本。

解决方案:

使用一下代码就可以

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);

public void SetCursorPosofTextBox(TextBox txb,int pos)
{
    txb.Focus();
    SendMessage(txb.Handle,177,pos,pos);
}

调用:

SetCursorPosofTextBox(this.textBox1,3);

Contributors: FHL