您必须创建一个自定义算法来解决这个问题。你没有写任何东西,我不能为你写,因此我将只包括基本部分和需要考虑的最重要的问题:
private void richTextBox1_Click(object sender, EventArgs e)
{
int selectionFirst = richTextBox1.SelectionStart;
}
您必须依靠Click Event
给定的RichTextBox
(richTextBox1
从现在开始)来获取Selection
(selectionFirst
)的起始索引。
您必须创建一个函数来向前和向后分析给定索引中的整个字符串,直到找到逗号或第一个/最后一个字符。此函数的输出将是第一个 ( indexFirst
) 和最后一个 ( indexLast
) 索引。
使用这两个索引,您可以定义所需的选择范围:
richTextBox1.SelectionStart = indexFirst;
richTextBox1.SelectionLength = indexLast - indexFirst;
你有它。
--------- 更新整个代码
private int[] findFirstLastChar(int curIndex)
{
int[] outIndices = new int[3];
string curText = richTextBox1.Text;
if (curText.Trim().Length < 1)
{
return outIndices;
}
int maxVal = 0;
int iniVal = curIndex;
bool completed = false;
int count0 = 0;
do
{
count0 = count0 + 1;
if (count0 == 1)
{
//Backwards
}
else
{
//Forwards
maxVal = curText.Length - 1;
}
completed = false;
int count1 = curIndex;
if (count1 == maxVal)
{
outIndices[count0] = count1;
}
else
{
do
{
if (count0 == 1)
{
count1 = count1 - 1;
if (count1 <= maxVal)
{
completed = true;
}
}
else
{
count1 = count1 + 1;
if (count1 >= maxVal)
{
completed = true;
}
}
if (count1 >= 0 && count1 <= curText.Length)
{
if (curText.Substring(count1, 1) == "," || completed)
{
outIndices[count0] = count1;
if ((count0 == 1 && !completed) || (count0 == 2 && completed))
{
outIndices[count0] = outIndices[count0] + 1;
}
break;
}
}
} while (!completed);
}
} while (count0 < 2);
return outIndices;
}
在点击事件中:
private void richTextBox1_Click(object sender, EventArgs e)
{
int[] indices = findFirstLastChar(richTextBox1.SelectionStart);
if (indices[1] <= indices[2])
{
richTextBox1.SelectionStart = indices[1];
richTextBox1.SelectionLength = indices[2] - indices[1];
}
}