Reputation: 446
I'm working on a text editor which includes a RichTextBox
. One of the features that I want to implement is to show in a TextBox
the current Line and Column of the caret of the forementioned RichTextBox
at any moment.
Here's part of the code that I use (the rest of my code has nothing to do with my issue):
int selectionStart = richTextBox.SelectionStart;
int lineFromCharIndex = richTextBox.GetLineFromCharIndex(selectionStart);
int charIndexFromLine = richTextBox.GetFirstCharIndexFromLine(lineFromCharIndex);
currentLine = richTextBox.GetLineFromCharIndex(selectionStart) + 1;
currentCol = richTextBox.SelectionStart - charIndexFromLine + 1;
At this point, I should mention that when someone is using a RichTextBox
, there are three ways that the caret can change location:
Text
of the RichTextBox
RichTextBox
The code that I posted above works with no issues in the first two cases. However, it doesn't really work in the third case.
I tried using the Click
event and I noticed that the selectionStart
variable would always get the value of 0, which means that I always get the same and wrong results. Moreover, using the same code on other events like MouseClick
and MouseUp
did not solve my problem since selectionStart
is 0 even in the duration of these events.
So, how can I get the current Line and column everytime the user clicks on the RichTextBox
?
Upvotes: 1
Views: 925
Reputation: 22406
You want something like:
private void richTextBox1_MouseUp(object sender, MouseEventArgs e)
{
RichTextBox box = (RichTextBox)sender;
Point mouseLocation = new Point(e.X, e.Y);
box.SelectionStart = box.GetCharIndexFromPosition(mouseLocation);
box.SelectionLength = 0;
int selectionStart = richTextBox.SelectionStart;
int lineFromCharIndex = box.GetLineFromCharIndex(selectionStart);
int charIndexFromLine = box.GetFirstCharIndexFromLine(lineFromCharIndex);
currentLine = box.GetLineFromCharIndex(selectionStart) + 1;
currentCol = box.SelectionStart - charIndexFromLine + 1;
}
Upvotes: 1
Reputation: 70652
It seems to me that what you really want is to handle the TextBoxBase.SelectionChanged
event. Then any action that causes the selection to change will invoke your code, and as an added benefit the current selection will have been updated by the time your event handler is called, and you'll be assured of getting correct values.
If that does not address your specific need, then I must not be understanding the question. In that case, please provide a good, minimal, complete code example that shows clearly what you're trying to do, with a precise description of what that code does and how that's different from what you want it to do.
Upvotes: 1