Click here to Skip to main content
15,890,690 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I am developing a notepad application using WPF. How can I get the current cursor position in a textbox and display it in the statusbar button.

Any help is greatly appreciated.

Thanks.
Posted
Updated 4-Aug-11 23:48pm
v2
Comments
Slacker007 5-Aug-11 5:48am    
Edited for readability and formatting.

Use SelectionStart. Returns an integer that represents the starting position on the textbox at that point.
Also, use the TextBoxSelectionChanged event. textBox1 in my example:

private void textBox1_SelectionChanged(object sender, RoutedEventArgs e)
{
   int s = textBox1.SelectionStart;

   // get the first status bar item
   System.Windows.Controls.Primitives.StatusBarItem item = (System.Windows.Controls.Primitives.StatusBarItem)this.statusBar1.Items[0];

   // get the content textblock of the status bar item
   item.Content = s.ToString();
}


I've only used one item in my status bar, but you can change the relevant item by changing the
this.statusBar1.Items[0];
 
Share this answer
 
v3
Comments
Sergey Alexandrovich Kryukov 5-Aug-11 5:59am    
Basically correct, so what? (Actually, it should be CaretIndex). OP needs to show position in the status bar.
Please see my solution -- it is tested and works.
--SA
UJimbo 5-Aug-11 6:19am    
Changed answer to suit WPF
No, you're not developing "notepad" application. Notepad already exists and is so rudimentary that, yes, a development of some text editor still makes some sense.

You can solve this problem like that:
C#
internal 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;
} //InquireCaretPosition


This code should be written in class inheriting from TextBox.

Another problem: on what events to show the caret position in the status bar?

1) Overridden method OnSelectionChanged;
2) When your text box control instance is first shown;
3) If you have more then one text box controls; when you select/show one of them.

If I'm not much mistaken, it will cover all cases.

—SA
 
Share this answer
 
v4
Check the TextBox::CaretIndex property.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 5-Aug-11 6:00am    
Basically correct, so what? OP needs to show position in the status bar.
Please see my solution -- it is tested and works.
--SA
YvesDaoust 5-Aug-11 6:05am    
@SAKryukov: anything against correct solutions ???

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