【问题标题】:Get the substring of the text by using SelectionStart使用 SelectionStart 获取文本的子字符串
【发布时间】:2014-07-16 15:19:05
【问题描述】:

当我在键盘上用箭头移动光标时,我想获取Windows窗体的RichTextBox中文本的子字符串。

    private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
    {
        string wholeText = richTextBox1.Text;
        if (wholeText.Length >0)
        {
            int positionBegin = richTextBox1.SelectionStart;
            SelectedText = wholeText.Substring(positionBegin);
        }
    }

但这是不正确的。例如,我输入了以下句子:

你好吗?

我想得到子字符串

你在做什么?

有两种方法。

  • 一个是从右到左,说我把光标移到句尾,用左箭头移动到字母y之前停住。我得到了

ou doing?

  • 或者从左到右,假设我将光标移动到句子的开头,使用右箭头移动并停止在字母y之前。我得到了

    you doing?

    案例一缺少字母y'. Case two added a white space beforey`。

我尝试对索引 +1 或 -1,但它生成了“IndexOutOfRangeException”。 使用SelectionStart有什么问题吗?

【问题讨论】:

  • 请改用 KeyUp 事件,因为在您运行代码时,SelectionStart 位置尚未更改。或 SelectionChanged 事件。

标签: c# winforms


【解决方案1】:

使用 SelectionChanged 事件而不是 KeyDown。我将返回正确的子字符串,它还将处理鼠标选择。

【讨论】:

    猜你喜欢
    • 2015-08-06
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 2019-09-27
    • 2011-08-21
    • 2015-07-07
    • 1970-01-01
    相关资源
    最近更新 更多