如何在文本框中获取光标位置 [英] How to get cursor position in a textbox

查看:92
本文介绍了如何在文本框中获取光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用WPF开发记事本应用程序.如何获取文本框中的当前光标位置,并将其显示在状态栏按钮中.

任何帮助将不胜感激.

谢谢.

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.

推荐答案

使用SelectionStart.返回一个整数,该整数表示该点在文本框中的起始位置.
另外,使用TextBoxSelectionChanged事件.在我的示例中为textBox1:

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];


来更改相关项.不,您不是在开发记事本"应用程序.记事本已经存在并且非常基础,是的,对某些文本编辑器的开发仍然有意义.

您可以这样解决此问题:
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:
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



此代码应使用从TextBox继承的类编写.
另一个问题:在状态栏上显示插入符号位置的事件有哪些?

1)覆盖方法OnSelectionChanged;
2)首次显示文本框控件实例时;
3)如果您有多个文本框控件;当您选择/显示其中之一时.

如果我没记错的话,它将涵盖所有情况.

—SA



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


检查TextBox :: CaretIndex属性.
Check the TextBox::CaretIndex property.


这篇关于如何在文本框中获取光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆