How do I create a Find form for a RichTextBox?

若如初见. 提交于 2019-12-24 08:31:03

问题


I would want to search up, down, and match case if possible. Even links to get me started would be appreciated.


回答1:


Not sure about the up searching but as far as finding you can use something like this

int selStart = ControltoSearch.SelectionStart;
int selLength = ControltoSearch.SelectionLength;
int newLength = SearchFor.Length;

int newStart = searchIn.IndexOf(SearchFor, selStart + selLength, compareType);

ControltoSearch.SelectionStart = newStart >= 0 ? newStart : 0;
ControltoSearch.SelectionLength = newLength;
ControltoSearch.ScrollToCaret();
ControltoSearch.Focus();

return newStart;

For matched case you can use String.ToLowerInvariant() on both the search in text and the search for text otherwise String.Contains() is case sensitive

searchIn.ToLowerInvariant().Contains(SearchFor.ToLowerInvariant())



回答2:


You could use the "Find" method on the Rich Text Box itself.

If you setup a form with a check box for "Match Case" and a check box for "Search Up" and have added a property on your find form called ControlToSearch which takes in a RichTextBox control you could do something like the following:

RichTextBoxFinds options = RichTextBoxFinds.None;

int from = ControlToSearch.SelectionStart;
int to = ControlToSearch.TextLength - 1;

if (chkMatchCase.Checked)
{
    options = options | RichTextBoxFinds.MatchCase;
}
if (chkSearchUp.Checked)
{
    options = options | RichTextBoxFinds.Reverse;
    to = from;
    from = 0;
}

int start = 0;
start = ControlToSearch.Find(txtSearchText.Text, from, to, options);

if (start > 0)
{
    ControlToSearch.SelectionStart = start;
    ControlToSearch.SelectionLength = txtSearchText.TextLength;
    ControlToSearch.ScrollToCaret();
    ControlToSearch.Refresh();
    ControlToSearch.Focus();
}
else
{
    MessageBox.Show("No match found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}


来源:https://stackoverflow.com/questions/837331/how-do-i-create-a-find-form-for-a-richtextbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!