Oussama Zebar
Oussama Zebar

Reputation: 43

How to Search a Text on a WebBrowser?

I'm beginner in C# and I have an issue. I need to popup a message box each time I find an occuracy in a webBrowser control after doing a search request, the occuracy will be selected at this time. I'm using a timer to refresh the webBrowser and launch the search again. It's like a notification system.

using System;
using System.Windows.Forms;
using mshtml;

namespace websearch
{

public partial class Form1 : Form
{
    Timer temp = new Timer();
    //Timer refreshh = new Timer();
    public Form1()
    {        
        InitializeComponent();
        temp.Tick += new EventHandler(refreshh_Tick);
        temp.Interval = 1000 * 5;
        temp.Enabled = true;
        temp.Start();
        WebBrowser1.Navigate("http://stackoverflow.com/");
    }

    void refreshh_Tick(object sender, EventArgs e)
        {
            WebBrowser1.Refresh();
            WebBrowser1.DocumentCompleted += Carder_DocumentCompleted;
        }

    private void Carder_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            FindNext("C#", WebBrowser1);
            temp.Tick += refreshh_Tick;
        }
    public void FindNext(string text, WebBrowser webBrowser2)
        {

            IHTMLDocument2 doc = webBrowser2.Document.DomDocument as IHTMLDocument2;
            IHTMLSelectionObject sel = doc.selection;
            IHTMLTxtRange rng = sel.createRange() as IHTMLTxtRange;

            rng.collapse(false); // collapse the current selection so we start from the end of the previous range
            if (rng.findText(text))
              {
                rng.select();
                MessageBox.Show("Theire are new C# Question");              
              }

        }
    }

}

Upvotes: 3

Views: 11566

Answers (1)

Fun Mun Pieng
Fun Mun Pieng

Reputation: 6891

There are several ways to do this:

  1. Create a recursive function to parse through all the HtmlElements and check for the contents. If your required text exists, you can either select the element, or change the element style or do whatever else that you might want to do.

Eg:

public bool SearchEle(HtmlElement ele, string text)
{
    foreach (HtmlElement child in ele.Children)
    {
        if (SearchEle(child, text))
            return true;
    }
    if (!string.IsNullOrEmpty(ele.InnerText) && ele.InnerText.Contains(text))
    {
        ele.ScrollIntoView(true);
        return true;
    }

    return false;
}
  1. You use webBrowser2.Document.Body.InnerText and do a string search. This is if you're not going to actually visually highlight the text, but just want to find the text.

On another note, you might want to move the code WebBrowser1.DocumentCompleted += Carder_DocumentCompleted; to Form1() constructor instead of doing it each time the refresh function refreshh_Tick is called.

Upvotes: 6

Related Questions