Tuesday, July 26, 2011

How to Use the WebBroswer Control

WebBroswer control could be used in WPF applications and Windows Form applications. However, there are quite difference while you try to apply it to these two type of applications. This document will focus on these difference then the complete usage of them.

If you are more interest in more detail about how the control does please go to the MSDN web site : WebBrowser Control (Windows Forms) , WebBrowser Control (WPF) , WebBrowser Control (Windows Phone 7)

In Windows Form applications, you can implement a WebBrowser instance and use it without add it into your windows form.

WebBrowser control reside in System.Windows.Forms (in System.Windows.Forms.dll)

You can use Nagivate() method or DocumentText, DoucmentStream properties to set its HTML contents.

You can use Document property to get an HtmlDocument representing the Web page currently displayed in the WebBrowser control.

Or you can use DocumentText or DocumentStream properties to get its HTML contents.

private void tbxSearchedWord_TextChanged(object sender, EventArgs e)
{    // implement a new WebBrowser instance
    System.Windows.Forms.WebBrowser queryWebBrowsr =
                      new System.Windows.Forms.WebBrowser();
    // add a even handeler to deal with when the query is completed
    queryWebBrowsr.DocumentCompleted +=
     new WebBrowserDocumentCompletedEventHandler(this.queryWebBrowsr_DocumentCompleted);
    // give the query url
    System.Uri SearchUri =
             new System.Uri(String.Format("http://www.google.com/dictionary?langpair=zh-TW|en&q={0}&hl=en&aq=f", this.tbxSearchedWord.Text), UriKind.RelativeOrAbsolute);
    // start to browser it
    queryWebBrowsr.Navigate(SearchUri);
}
 

private void queryWebBrowsr_DocumentCompleted(object sender,WebBrowserDocumentCompletedEventArgs e)
{

    try
    {
        // retrieve the WebBrowser object from sender
        System.Windows.Forms.WebBrowser queryWebBrowsr =
                                            (System.Windows.Forms.WebBrowser)sender;
        string queryWebBrowserResult = queryWebBrowsr.DocumentText;
         // retrieve result
        if (queryWebBrowsr.Document.GetElementById("pr-root") != null)
        {
            string DictResult =
                        queryWebBrowsr.Document.GetElementById("pr-root").InnerHtml;
            string replaceStr = @"style=""DISPLAY: none""";
            DictResult = DictResult.Replace(replaceStr, "");
            replaceStr = @"""/dictionary/";
            string replacedStr = @"""http://www.google.com/dictionary/";
            DictResult = DictResult.Replace(replaceStr, replacedStr);
            this.webBrowserDict.DocumentText = DictResult;           
        }
        else
        {
            this.webBrowserDict.DocumentText = String.Format("No dictionary translations were found for: <strong>{0}</strong>", this.tbxSearchedWord.Text);
        }

    }
    catch (Exception exp)
    {
        string msg = exp.Message;
        MessageBox.Show(msg);
    }

}

In WPF applications, you can implement a WebBrowser instance and get no error when you compile them and run them. However, the even will not fire which means it is not working unless you add you WebBrowser control into your windows form (a hidden object is ok).

WebBrowser control reside in PresentationFramework (in PresentationFramework.dll)

You can use Nagivate(), NagivateToText(), NagivateToStream() methods or Sourceproperty to set its HTML contents.

You can use Document property to get an Microsoft.mshtml.HtmlDocument (in Microsoft.mshtml.dll) representing the Web page currently displayed in the WebBrowser control.

private void tbxSearchedWord_TextChanged(object sender, TextChangedEventArgs e)
{
    // implement a new WebBrowser instance
    System.Windows.Controls.WebBrowser queryWebBrowsr =
                     new System.Windows.Controls.WebBrowser();
    // add a even handeler to deal with when the query is completed
    // The even will not fire
    //   if you dynamiclly add a WebBrowser control in your WPF application
    queryWebBrowsr.LoadCompleted +=
        new LoadCompletedEventHandler(queryWebBrowsr_LoadCompleted);
    // add to your form
    //  (you have to add the control into your form in order to fire the evens)
    this.HiddenControlGrid.Children.Add(queryWebBrowsr);
    // give the query url
    System.Uri SearchUri =
              new System.Uri(String.Format("http://www.google.com/dictionary?langpair=zh-TW|en&q={0}&hl=en&aq=f", this.tbxSearchedWord.Text), UriKind.RelativeOrAbsolute);
    // start to browser it
    queryWebBrowsr.Navigate(SearchUri);
}

// The even will not fire
//   if you dynamiclly add a WebBrowser control in your WPF application

void queryWebBrowsr_LoadCompleted(object sender, NavigationEventArgs e)
{
    try
    {
        // retrieve the WebBrowser object from sender
        System.Windows.Controls.WebBrowser queryWebBrowsr = (System.Windows.Controls.WebBrowser)sender;
        // retrieve the HTMLDocument object from WebBrowser

        mshtml.HTMLDocument htmlDom = new mshtml.HTMLDocument();
        htmlDom = (mshtml.HTMLDocument)queryWebBrowsr.Document;

        string queryWebBrowserResult = htmlDom.toString();
        // retrieve result
        if (htmlDom.getElementById("pr-root") != null)
        {
            string DictResult = htmlDom.getElementById("pr-root").innerHTML;
            string replaceStr = @"style=""DISPLAY: none""";
            DictResult = DictResult.Replace(replaceStr, "");
            replaceStr = @"""/dictionary/";
            string replacedStr = @"""http://www.google.com/dictionary/";
            DictResult = DictResult.Replace(replaceStr, replacedStr);
            this.webBrowsrDict.NavigateToString(DictResult);

        }
        else
        {
            this.webBrowsrDict.NavigateToString(String.Format("No dictionary translations were found for: <strong>{0}</strong>", this.tbxSearchedWord.Text));
        }
    }
    catch (Exception exp)
    {
           
string
 msg = exp.Message;
           
MessageBox
.Show(msg);
    }
}
 

// retrieve html segment
private string RetrieveHtmlSegment(string htmlDocumentText, string matchStart, stringmatchEnd)
{
    int strPosition = htmlDocumentText.IndexOf(matchStart);
    if (strPosition >= 0)
    {
        
int
 endPosition = htmlDocumentText.IndexOf(matchEnd, strPosition);
       
return
 (htmlDocumentText.Substring(strPosition, endPosition - strPosition));
    }
    else
    {
        
return "";
    }
}

No comments:

Post a Comment