C# | 如何通过光标位置选择文本框中的单词?

Cha*_*eus 0 c# textbox cursor winforms

在 Windows 窗体中,使用 C#,如何根据光标位置选择(例如,实际上突出显示文本,使其可供 .SelectedText 属性访问)一个单词?

这就是我想要做的。我有一个文本框,用户当前可以通过突出显示它来选择一个单词。然后他们可以对这个词执行各种操作,但我想让它更简单。

我希望这样做,以便他们可以简单地将光标放在单词内,应用程序将选择光标所在的单词。

提前致谢!

Mic*_*cki 5

您可以使用SelectionStartandSelectionLength但您可能需要从光标位置找到下一个空格,然后反转文本框的内容并从“更改后的光标”位置找到下一个“空格”,然后使用上述两种方法。

这也将起作用

int cursorPosition = textBox1.SelectionStart;
int nextSpace = textBox1.Text.IndexOf(' ', cursorPosition);
int selectionStart = 0;
string trimmedString = string.Empty;
// Strip everything after the next space...
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;
Run Code Online (Sandbox Code Playgroud)