您可以使用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)