如何知道插入符号在文本框(文本块)中的当前位置,以编程方式选择某个单词

本文关键字:文本 位置 编程 方式 选择 单词 符号 插入 何知道 | 更新日期: 2023-09-27 18:30:51

例如,在 TextBox(TextBlock) C# WPF 中键入时

美丽的大自然

美丽_(在这里,在输入自然之前,我想知道插入符号当前位置的索引。假设"_"下划线现在闪烁插入符号)

我正在尝试实现的是按左移按钮设置选择的起始位置,并通过按右移按钮设置结束位置这样我就可以以编程方式选择仅在文本框中的最新(最近)单个单词以在某处使用。

我一直在用下面的简单代码尝试几种方法,但失败了,互联网上没有类似的情况。

或者作为更好的解决方案,是否有人知道一种方法,在完全输入美丽的自然并仅按一次键按钮以仅以编程方式选择最近的单词"自然"之后?

如果有人为此分享卓越,我将不胜感激。

int startinglocation;
int endinglocation;
int selectionlength;

private void textBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key==Key.LeftShift) After typing Beautiful in textBox,
            {
            
                // To know the current location of Caret, Some wise instruction is needed here
            }
            if (e.Key == Key.RightShift) // After typing Nature in textBox,
            {

                // To know the current location of Caret, Some wise instruction is needed here
                int selectionlength=endinglocation- startinglocation;                    
                textBox.Select(startinglocation, selectionlength);
            }
        
    }
<小时 />

解决

后者是更好的解决方案,只需按尼古拉斯·泰勒(Nicolas Tyler)的按键即可选择最近的最新单词。谢谢泰勒先生。

private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.RightShift)
        {
            selectWord();
        }
    }
    private void selectWord()
    {
        int cursorPosition = textBox1.SelectionStart;
        int nextSpace = textBox1.Text.IndexOf(' ', cursorPosition);
        int selectionStart = 0;
        string trimmedString = string.Empty;
        if (nextSpace != -1)
        {
            trimmedString = textBox1.Text.Substring(0, nextSpace);
        }
        else
        {
            trimmedString = textBox1.Text;
        }

        if (trimmedString.LastIndexOf(' ') != -1)
        {
            selectionStart = 1 + trimmedString.LastIndexOf(' ');
            trimmedString = trimmedString.Substring(1 + trimmedString.LastIndexOf(' '));
        }
        textBox1.SelectionStart = selectionStart;
        textBox1.SelectionLength = trimmedString.Length;
    }

如何知道插入符号在文本框(文本块)中的当前位置,以编程方式选择某个单词

使用

TextBox.SelectionStart

它为您提供当前光标位置,当您使用 WinForms 时的位置。

当您使用演示基础时,您可以使用

TextBox.CaretIndex

如 MSDN TextBox.CaretIndex 中所述。