从c#中的Richtextbox中选择文本
本文关键字:选择 文本 Richtextbox 中的 | 更新日期: 2023-09-27 17:50:52
我想选择一个richtextbox文本的最后一个'{'和'}'之间的文本。我有下一个代码,但我有一个错误的"LastIndexOf"函数,我不知道如何修复它。有人能帮帮我吗?
private void highlightText()
{
mRtbxOperations.SelectionStart = mRtbxOperations.Text.LastIndexOf(@"{", 1, mRtbxOperations.SelectionStart);
mRtbxOperations.SelectionLength = mRtbxOperations.Text.IndexOf(@"}", mRtbxOperations.SelectionStart, mRtbxOperations.Text.Length - 1);
mRtbxOperations.SelectionBackColor = Color.LightBlue;
mRtbxOperations.SelectionFont = new Font(mRtbxOperations.SelectionFont, FontStyle.Underline);
mRtbxOperations.SelectionLength = 0;
}
LastIndexOf错误:
计数必须是正的,并且必须引用对象中的位置字符串、数组或集合。参数名称:count
您的LastIndexOf参数混乱,以及选择的长度,您需要减去起点以获得适当的长度。
试试更简单的版本:
int textStart = mRtbxOperations.Text.LastIndexOf(@"{",
mRtbxOperations.SelectionStart);
if (textStart > -1) {
int textEnd = mRtbxOperations.Text.IndexOf(@"}", textStart);
if (textEnd > -1) {
mRtbxOperations.Select(textStart, textEnd - textStart + 1);
mRtbxOperations.SelectionBackColor = Color.LightBlue;
}
}
看来你要跳出文本的界限了。当你获取子字符串或索引时,你总是应该使用字符串边界,或者子字符串边界。此外,您需要检查选择是否有效。
我将重写你的代码如下:
private void highlightText()
{
Selection selection = GetSelection(mRtbxOperations.Text);
if (selection == null)
return;
mRtbxOperations.SelectionStart = selection.Start;
mRtbxOperations.SelectionLength = selection.Length;
mRtbxOperations.SelectionBackColor = Color.LightBlue;
mRtbxOperations.SelectionFont = new Font(mRtbxOperations.SelectionFont,
FontStyle.Underline);
}
private static Selection GetSelection(string text)
{
int sIndex = text.LastIndexOf(@"{");
if (sIndex == -1)
return null;
int eIndex = text.IndexOf(@"}", sIndex);
if (eIndex == -1)
return null;
return new Selection(sIndex + 1, eIndex);
}
public class Selection
{
public int Start { get; set; }
public int End { get; set; }
public int Length
{
get
{
return End - Start;
}
}
public Selection(int startIndex, int endIndex)
{
this.Start = startIndex;
this.End = endIndex;
}
}