C# 能不能获取文本框光标当前所在的位置,及所在的行

2024-12-28 19:46:47
推荐回答(2个)
回答1:

[DllImport("user32.dll", EntryPoint = "SendMessageA")]
private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, StringBuilder lParam);

[DllImport("user32 ")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);

private void button2_Click(object sender, EventArgs e)
{
int EM_LINEINDEX = 0xBB;
int EM_LINEFROMCHAR = 0xC9;
int EM_GETSEL = 0xB0;
int EM_GETLINE = 0xC4;

//通过API完成很简单的
//通过向文本框传递EM_LINEFROMCHAR消息可以得到光标所在的行数
int Row = (int)SendMessage(textBox1.Handle, EM_LINEFROMCHAR, -1, 0);

////通过向文本框传递EM_GETSEL消息可以得到编辑控件中一段选定内容的起点与终点字符的个数
//int s = (int)SendMessage(textBox1.Handle, EM_GETSEL, 0, 0);
////通过向文本框传递EM_GETSEL消息可以得到每一行的第一个字符在全文中的字符序号
//int li = (int)SendMessage(textBox1.Handle, EM_LINEINDEX, -1, 0);
//int Col = (s & 0xffff) - li + 1;

StringBuilder currentLine = new StringBuilder(256);
SendMessage(textBox1.Handle, EM_GETLINE, Row, currentLine);
MessageBox.Show(currentLine.ToString());
}

回答2:

C#有个Focus()方法~是获取当前文本的焦点·就是光标