Blog

Hosted Browser App: Wondows Form and WebBrowser

Posted by Preetham Mukhatira Blogs | Windows Forms C# Aug 01, 2007
With applications moving to the web and an increasing cohesion between Web-based applications and Windows based applications, we often find ourselves in a situation where our windows application interacts with a web page. The web page can be hosted by an app, either built by the same team or could be a 3rd party website. Either way, we find web and windows application interacting and a need for bi-directional communication.

In this article I will demonstrate 3 aspects of hosting a web page in a windows app:

1.       Hosting a browser and navigating to a web page.

2.       Windows form calling javascript function on the web page.

3.       Web page calling a function defined in the windows form hosting the webpage.

Scenario: In our windows application, we are viewing customer data in a grid. Upon selecting a row, we would like to pass the customer data to a web page. The web page collects the information, displays it, updates the database and closes upon completion. The page then tells the windows app if the save was successful or not.

In the following steps will define how to navigate to a web page from a windows app.

Step 1: Create a windows form (hosted-browser form) that will host the WebBrowser control.

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

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

    public partial class FrmHostedBrowser : Form

    {

      public String url = new String();

      public WebBrowser browser = new WebBrowser();

 

private void FrmHostedBrowser_Load(object sender, EventArgs e)

      {

          browser.Navigate(url);

      }

      .

      .

      .

    }

 

The class must have the ComVisible attribute to enable communication between the form that hosts the webbrowser control and the html document. We will describe this in the following step.

 

Step 2: Use the Hosted browser form to navigate to a web page.

In the right click event handler for the grid, have the following code:

private void gridRowContextMenu_Click(object sender, EventArgs e)

{

      //get the customer information from the selected row

foreach (DataGridViewRow row in BacklogManagementGrid.SelectedRows)

{

      //get the name , account_number

}

//open the hosted browser form, navigate to the page contents

frmSaveCustomer = new FrmHostedBrowser ();

frmSaveCustomer.url = “http://www.mysite.com/savecustomer.aspx”;

      frmSaveCustomer.browser.WebBrowserClose += new WebBrowserCloseEventHandler(this.CloseHostedBrowserWindow);

      frmSaveCustomer.WebBrowser.AllowWebBrowserDrop = false;

      frmSaveCustomer.WebBrowser.IsWebBrowserContextMenuEnabled = false;

      frmSaveCustomer.WebBrowser.ObjectForScripting = this;

      frmSaveCustomer.WebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(this.OnDocumentLoadCompleteHandler);

            frmSaveCustomer.Show();

           

}

 

Notice how we set the ObjcetForScripting to the form. This reference fecelitates the communication between Form and WebBrowser and will enable JavaScript to call a method in the form. To enable this communication we set the ComVisible in the previous section.

We will find out how this works in Step 3.

Step 3: Invoke a script from the windows form

Also notice we have defined two event handlers:

1.       WebBrowserCloseEventHandler: Used to close the form when the browser is closed

  private void CloseHostedBrowserWindow(object sender, EventArgs e)

        {

            if (frmSaveCustomer != null && frmSaveCustomer.Visible)

            {

                frmSaveCustomer.Close();

            }

            frmSaveCustomer = null;

        }

2.       WebBrowserDocumentCompletedEventHandler: This event is fired when the web page load is complete. This event is useful if we would like to invoke some JavaScript on the web page from the windows form.  In our scenario, we will invoke the script LoadCustomer and pass the customer information (name, account number) we obtained from the grid in step 1.

private void OnDocumentLoadCompleteHandler(object sender, WebBrowserDocumentCompletedEventArgs e)

{

if (frmMailSend != null)

{

frmSaveCustomer.browser.Document.InvokeScript("LoadCustomer", new string[] { name , account_number });

}

   }

LoadCustomer is defined in the aspx page that is loaded by the Hosted browser.

The InvokeScript method can be called at any time after the document has been loaded and can call any JavaScript function defined in the page.

Step 3: Calling a method defined in the windows form(hosted-browser) from the web page javascript.

In the earlier example we noticed how the windows form can invoke a script on the web page. To implement the reverse, we first define a method in the hosted-browser form.

private void FrmHostedBrowser_Notify(String message)

      {

          MessageBox.Show(message);

      }

 

Next, we define a javascript function in the aspx page to invoke the above function. The method is exposed to the javascript by invoking:

 window.external. FrmHostedBrowser_Notify(‘success’);

Step 4: The aspx web page

This section defines the aspx page(savecustomer.aspx).

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="savecustomer.aspx.cs" Inherits="SaveCustomer" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<script language="javascript">

 

 

function LoadCustomer(cname, caccnumber)

{

    //set the values in the page

    document.getElementById('Control1_txtName').value = cname;

    document.getElementById('Control1_txtAccount').value = caccnumber;

}

 

function SaveCustomer()

{

      //implement the logic to save

      //if success, call the method in the windows form

      window.external. FrmHostedBrowser_Notify(‘success’);

      //close the window

      CloseWindow()

}

 

function CloseWindow()

{

    window.open('','_self','');//to close without prompt

    window.close();

}

</script>

<body>

    <form id="frmTest" runat="server">

      .//text boxes go here

      .

      .

<input id="btnSave" type="button" value="Save" onclick="SaveCustomer()" style="width: 60px"/>

      <input id="btnClose" type="button" value="Close" onclick="CloseWindow()" style="width: 60px"/>

    </form>

</body>

</html>

 

From the code we notice that the LoadCustomer method (in the previous step) is called by the windows app to set the customer name and account number fields on the webpage.

Also, the calls a method in the windows form to notify the status of the save.

Also, the event handler WebBrowserCloseEventHandler identified in Step 3 will execute when the Close button is clicked and the browser is closed.

This example is an illustration of some of the scenarios and the mechanisms involved. Using these mechanisms, various other scenarios can be implemented.
COMMENT USING
PREMIUM SPONSORS
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.
SPONSORED BY
  • MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.