开发者

C# How to program find function

开发者 https://www.devze.com 2023-01-25 16:59 出处:网络
I have a C# program that utilizes a find function however it is able to find the word but does not highlights the found word in the richTextBox.

I have a C# program that utilizes a find function however it is able to find the word but does not highlights the found word in the richTextBox.

Can someone please advise me on the codes?

Thanks.

Find Function Class Form:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using Syst开发者_如何学Pythonem.Text;
using System.Windows.Forms;

namespace Syscrawl
{
public partial class Find_Form : Form
{
    FTK_Menu_Browsing_History fmbh = new FTK_Menu_Browsing_History();

    public Find_Form()
    {
        InitializeComponent();
    }

    public void searchButton_Click(object sender, EventArgs e)
    {
        string s1 = fmbh.getSearchBrowsing().ToLower();
        string s2 = textBoxSearch.Text.ToLower();

        if (s1.Contains(s2))
        {
            MessageBox.Show("Word found!");

            this.fmbh.richTextBoxBrowsing.Find(s2);
            this.fmbh.richTextBoxBrowsing.SelectionLength = s2.Length;
            this.fmbh.richTextBoxBrowsing.SelectionColor = Color.Red;
            this.Close();
        }
        else
        {
            MessageBox.Show("Word not found!");
        }
    }
}
}


You need to select what you are looking for first. This:

int offset = s1.IndexOf(s2);
richTextBox1.Select(offset, s2.Length);

After that you can make the whole highlightining. Another tip, to prevent the flickering in the selection process, use this code in your form:

protected override void WndProc(ref Message m)
{
    if (m.Msg == 0) {
        if (!_doPaint)
            return;
    }

    base.WndProc(ref m);
} 

Before selecting anything set _doPaint to false and after the selection set it to true.

Hope I can help!


You need to call s1.IndexOf(s2, StringComparison.CurrentCultureIgnoreCase) to find the position of the match.

Also, it looks like your Find form creates its own instance of the History form; it doesn't use the existing instance.
You should consider accepting a constructor parameter.

0

精彩评论

暂无评论...
验证码 换一张
取 消