How to move the cursor to the correct line in a RichTextBox

I'm sure there is a really simple way of doing this, but this works out for me. Please write a comment and tell me how it's supposed to be done if this isn't the best way (which I'm sure it isn't ;)

public void SetCaretLine(int linenr)


      if(linenr > this.richTextBox1.Lines.Length)


            MessageBox.Show("Line " + linenr + " is out of range.");




      int row = 1;

      int charCount = 0;

      foreach(string line in richTextBox1.Lines)


            charCount+=line.Length + 1;


            if(row == linenr)


                  //set the caret here

                  this.richTextBox1.SelectionStart = charCount;





Well? I guess there's a win32 api lurking in the shadows that does this in 1 or 2 lines of code - then show me already!

1 Comment

  • The magic API you're looking for is SendMessage, with the EM_LINEINDEX constant.

    public const int EM_LINEINDEX = 0xHBB;


    public static extern int SendMessage(

    int hWnd,

    uint Msg,

    int wParam,

    int lParam );

Comments have been disabled for this content.