如何在记事本C#winforms中执行Find / FindNext操作

时间:2011-07-30 11:36:19

标签: c# .net winforms programmers-notepad

请有人建议我如何在C#中的记事本程序中执行find / findNext操作。我想在RichTextBox中搜索所有出现的字符串,并在点击findNext按钮时突出显示每个字符串。

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

我在C#中创建了一个记事本克隆,它实现了与Window的记事本相同的find / findnext操作。你可以在这里找到来源:

http://www.simplygoodcode.com/2012/04/notepad-clone-in-net-winforms.html

以下是函数中代码的代码:

    private string _LastSearchText;
    private bool _LastMatchCase;
    private bool _LastSearchDown;

    public bool FindAndSelect(string pSearchText, bool pMatchCase, bool pSearchDown) {
        int Index;

        var eStringComparison = pMatchCase ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;

        if (pSearchDown) {
            Index = Content.IndexOf(pSearchText, SelectionEnd, eStringComparison);
        } else {
            Index = Content.LastIndexOf(pSearchText, SelectionStart, SelectionStart, eStringComparison);
        }

        if (Index == -1) return false;

        _LastSearchText = pSearchText;
        _LastMatchCase = pMatchCase;
        _LastSearchDown = pSearchDown;

        SelectionStart = Index;
        SelectionLength = pSearchText.Length;

        return true;
    }

此方法位于主窗体上。它说明了“查找”对话框中的选项。它存储参数值,以便以后能够执行“查找下一个”/ F3。您看到的一些属性SelectionStartSelectionLengthContent基本上是TextBox的{​​{1}},SelectionStart的别名,和SelectionLength属性。