Click here to Skip to main content
15,898,134 members
Please Sign up or sign in to vote.
3.00/5 (3 votes)
See more:
I need to be notified when caret inside a TextBox is moved by the user (selection, mouse click, keyboard input, arrows) OR programmatically (my TextBox also receives data from remote source).
I'm unable to find a simple way to make this job, someting like Java CaretUpdateListener or some event managed by the system...
I would appappreciate some help, I've googled for a solution but I'm new to WPF, so maybe one little hint... :-}
Thank you in advance,
Maurizio.

P.s.: sorry for bad english.
Posted

1 solution

I remembered that I completely solved this problem, so I looked at my old code and found it. All the changes in caret position will be caught if you override the virtual method TextBox.OnSelectionChanged. You can also handle the event SelectionChanged, of course. I prefer to subclass the control and advice you to do so, as you are implemented a bit more advanced features. For a bonus, I'll show you how to calculate caret position in terms of line/column. Assuming you subclass the text box, it will look like this:

C#
partial class MyTextBox : TextBox {

     void InquireCaretPosition(out Position line, out Position column) {
         line = 0; column = 0;
         int caret = this.CaretIndex;
         int iLine = this.GetLineIndexFromCharacterIndex(caret);
         if (iLine < 0) iLine = 0;
         line = iLine;
         int firstChar = this.GetCharacterIndexFromLineIndex(iLine);
         if (firstChar  0) firstChar = 0;
         column = caret - firstChar;
     }

     protected override void OnSelectionChanged(RoutedEventArgs e) { //for example
         base.OnSelectionChanged(e);
         ShowPosition();
     }

     void ShowPosition() {
        int line, column;
        InquireCaretPosition(out line, out column);
        //show line and column in status line or something like that    
     }

     //...

}


Don't forget to show position on some other events, such as when your text box is shown, etc.

Good luck,
—SA
 
Share this answer
 
v2
Comments
VJ Reddy 17-Apr-12 8:05am    
Nice answer. 5!
Sergey Alexandrovich Kryukov 17-Apr-12 11:16am    
Thank you, VJ.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900