- 获得光标所在的行号
- 获得光标所在的列号
- 设置光标到指定行号
- 设置光标到指定列号
http://www.huifangseo.com/blog/6/7.html
获得光标所在的行号和列号
方法1
int SelStart = richTextBox1.SelectionStart; int Line = 1 + richTextBox1.GetLineFromCharIndex(SelStart); //行值 int Column = 1 + SelStart - (richTextBox1.GetFirstCharIndexFromLine(Line - 1));//列值 Text = string.Format("行{0} 列{1}", Line, Column);
方法2
using System.Runtime.InteropServices; private int EM_LINEINDEX = 0x00BB; private int EM_LINEFROMCHAR = 0x00C9; [DllImport("user32.dll", EntryPoint = "SendMessage")] public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam); public Point GetCaretPosition(TextBoxBase editControl) { int charIndex = (int)SendMessage(editControl.Handle, EM_LINEINDEX, -1, 0);//行值 int lineIndex = (int)SendMessage(editControl.Handle, EM_LINEFROMCHAR, charIndex, 0);//列值 return new Point(editControl.SelectionStart - charIndex, lineIndex); }
private void button2_Click(object sender, EventArgs e) { Point pt = GetCaretPosition(richTextBox1); Text = string.Format("行{0} 列{1}", pt.X + 1, pt.Y+1); }
http://bbs.csdn.net/topics/360049737
设置光标到指定行号
方法1 GetFirstCharIndexFromLine
//转到第三行 int Line = 3; richTextBox1.SelectionStart = richTextBox1.GetFirstCharIndexFromLine(Line - 1); richTextBox1.SelectionLength = 0; richTextBox1.ScrollToCaret(); richTextBox1.Focus();
方法2 SendMessage
//转到第3行 int Line = 3; richTextBox1.SelectionStart = SendMessage(richTextBox1.Handle, EM_LINEINDEX, Line - 1, 0); richTextBox1.SelectionLength = 0; richTextBox1.ScrollToCaret(); richTextBox1.Focus();
设置光标到指定列号
先转到指定行号,然后 加上当前光标的列号 richTextBox1.SelectionStart
private void jumpColumn(int Column) { int Line = Column; int charIndex = (int)SendMessage(richTextBox1.Handle, EM_LINEINDEX, Line - 1, 0); int lineIndex = charIndex + (int)SendMessage(richTextBox1.Handle, EM_LINEFROMCHAR, charIndex, 0); richTextBox1.SelectionStart = lineIndex; }
private void button4_Click(object sender, EventArgs e) { //转到第5行 第5列 richTextBox1.Focus(); jumpColumn(5); }