gpt4 book ai didi

C# RichTextBox 选择指定文本

转载 作者:太空狗 更新时间:2023-10-29 23:17:52 25 4
gpt4 key购买 nike

我有一个 RichTextBox,其中包含 - 例如 - 此文本:

"This is my Text"

现在我想在 RichTextBox 中“搜索”文本(字符串),例如:

"Text"

现在应该在 RichTextBox 中选择/突出显示“文本”(对于每个文本)..

有这样的东西:

myRichTextBox.Select();

但是这里我要设置一个StartPosition等等,但是我要搜索String!

我该怎么做? (搜索stackoverflow,没有找到类似的东西..)

最佳答案

     int start = 0;
int indexOfSearchText = 0;
private void btnFind_Click(object sender, EventArgs e)
{
int startindex = 0;

if(txtSearch.Text.Length > 0)
startindex = FindMyText(txtSearch.Text.Trim(), start, rtb.Text.Length);

// If string was found in the RichTextBox, highlight it
if (startindex >= 0)
{
// Set the highlight color as red
rtb.SelectionColor = Color.Red;
// Find the end index. End Index = number of characters in textbox
int endindex = txtSearch.Text.Length;
// Highlight the search string
rtb.Select(startindex, endindex);
// mark the start position after the position of
// last search string
start = startindex + endindex;
}
}




public int FindMyText(string txtToSearch, int searchStart, int searchEnd)
{
// Unselect the previously searched string
if (searchStart > 0 && searchEnd > 0 && indexOfSearchText >= 0)
{
rtb.Undo();
}

// Set the return value to -1 by default.
int retVal = -1;

// A valid starting index should be specified.
// if indexOfSearchText = -1, the end of search
if (searchStart >= 0 && indexOfSearchText >=0)
{
// A valid ending index
if (searchEnd > searchStart || searchEnd == -1)
{
// Find the position of search string in RichTextBox
indexOfSearchText = rtb.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None);
// Determine whether the text was found in richTextBox1.
if (indexOfSearchText != -1)
{
// Return the index to the specified search text.
retVal = indexOfSearchText;
}
}
}
return retVal;
}



private void textBox1_TextChanged(object sender, EventArgs e)
{
start = 0;
indexOfSearchText = 0;
}

如果您不理解这段代码,请查看这篇文章... http://www.dotnetcurry.com/ShowArticle.aspx?ID=146

关于C# RichTextBox 选择指定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7228088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com