WebBrowser Control in C#

 

To call web page from C# application, we have two approaches. One is by using HTTP Web request, which is best approach to just connect to database.

If we want to call win forms methods at server or if we want to display web page in win forms application we have to use WebBrowser control in C#.

In this article we discuss about how to use WebBrowser control in C# WIN forms application. Before creating windows application first create sample HTML Web page as shown below. 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 

<html> 

          <head> 

               <title>This is Sample HTML web page</title> 

 

               <script type="text/javascript" language="javascript">

 

                 function Hello() { 

                    window.external.Hello(); //Hello() is the C# method on win form application 

                  

 

              </script> 

        </head> 

       <body> 

            <h1>This is Sample HTML web page to check C# Web browser control</h1> 

           <input type="button" value="Click To Call C# method" onclick="Hello();" /> 

       </body> 

</html>

 

Host this Sample.htm web page on IIS server and get URL, here I got URL as " http://localhost/CSharpWebbrowserControl/Sample.htm ".

As shown above we are calling the Hello() javascript function when button click and in javascript function we are calling the Hello() C# method.

Now create sample C# windows project and drag & drop WebBrowser control. Add below code to the Form1.cs class. 

using System; 

using System.Security.Permissions; 

using System.Windows.Forms;

 

namespace CSharpWebbrowserControl 

{ 

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] 

    [System.Runtime.InteropServices.ComVisibleAttribute(true)] 

    public partial class Form1 : Form 

    { 

        public Form1() 

        { 

            InitializeComponent(); 

        }

 

        private void Form1_Load(object sender, EventArgs e) 

        { 

            webBrowser1.Navigate(new Uri("http://localhost/CSharpWebbrowserControl/Sample.htm")); 

            webBrowser1.ObjectForScripting = this; 

        }

 

        ///<summary> 

        /// this method called from Java Script 

        ///</summary> 

        public void Hello() 

        { 

            MessageBox.Show("Hello World......This is from C# to test Web Browser control"); 

        } 

    } 

}

 

As shown above we provided the Sample.htm web page URL to the WebBrowser control Navigate() method and we have C# Hello() method which is called from java script.

Now run the application and click on web page button which calls C# Hello() method from javascript.

                                                                                                           CSharpWebbrowserControl.zip (41.95 kb)