Tuesday, 19 April 2011

C# : Detecting cursor position in RichTextBox

When i was working on RichTextBox the main thing that i had to handle was counting lines and detecting cursor position. Now lets see how to get these things done. Let me tell you about how to detect cursor position.

You need to use:
RichTextBox.SelectionStart and RichTextBox.GetLineFromCharIndex()
But make sure you use instance method of RichTextBox class as show
here :GetLineFromCharIndex[^] and GetLineFromCharIndex[^]
    
private static int EM_LINEINDEX = 0xbb;

int index, line, col;

[DllImport("user32.dll")]

extern static int SendMessage(IntPtr hwnd, int message, int wparam, int lparam);   


[DllImport("user32.dll")]
This line of code shouldn't be written in any method or functions.
You will find detailed explanation here:
 DllImportAttribute[^]

Now main function that tells you current column and current row.
void detectCursorPos(){
index = richTextBox1.SelectionStart;
line = richTextBox1.GetLineFromCharIndex(index);
col = index - SendMessage(richTextBox1.Handle, EM_LINEINDEX, -1, 0);

this.label_column.Text = (++col).ToString();
this.label_row.Text = (++line).ToString(); }

You will find detailed explanation as given above.
Now all you have to do is just call this function behind any event handler, say key press.
It would looks like as follows.
private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e){
detectCursorPos();
}

Don't forget to register event handler!!!
this.richTextBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.richTextBox1_KeyPress);
This will register your handler with system.

Now put them together.
namespace Editor
{
public partial class Form1 : Form
{
int index, line, col;
       private static int EM_LINEINDEX = 0xbb; 
[DllImport("user32.dll")]

extern static int SendMessage(IntPtr hwnd, int message, int wparam, int lparam);

void detectCursorPos()
{
index = richTextBox1.SelectionStart;
line = richTextBox1.GetLineFromCharIndex(index);
col = index - SendMessage(richTextBox1.Handle, EM_LINEINDEX, -1, 0);

         this.label_column.Text = (++col).ToString();
         this.label_row.Text = (++line).ToString(); 
}
           private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
           {
              detectCursorPos();
           }
}
}

This simple.
Good luck.

1 comment: