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;

Join the conversation! Your thoughts help the community grow.