Use JavaScript Function in Window Application C#

This article explains how to use a JavaScript function in a C# Windows application. I have explained the following points:

  • How to use a JavaScript function in a Windows application
  • How to call C# code method from JavaScript in a Windows application

I have explained these points using an example. In my example I use a WebBrowser control of a Windows application.
 
Step 1: Initially create a new Windows based project. Execute Visual Studio 2010 then go to "File" -> "New" -> "Project..." then select "Windows" -> "Windows Forms Application".

Windows Form Application

Step 2: Then drag and drop a WebBrowser control to a Windows Forms form and also drag and drop a Print Dialog Control onto the form.

browser control

Step 3: Go to "Application" => "Add New Item" => "Add HTML page" to the debug folder of the Windows based application.

HTML page
 
Step 4: Write this code in HTML Page.

HTML Page code

Step 5: Then go to the code for the Windows Forms form and add the following attribute above the class of the Windows Forms form. For this you need to add the following namespace in your code.

using System.Runtime.InteropServices;

attribute

Step 6: Then write the following code in the Constructor of this form.

Code in Constructor
 Step 7: Then write this code in the Form Load method.

code in Form Load method
 
Step 8: Then write some code in WebBrowser document completed method.
  1. Initially add this code: this code contains simple html based report.

    html based report

  2. Then write the following code for the WebBrowser DocumentCompleted event.

    Web browser document

Step 9: After writing all that code you need to write the following method. This method is called by the JavaScript function.

The Method Access Specifier should be public.

Method access specifier
 
Step 10: Then got to the HTML page and write the following function. In this function call the C# code method using window.external.PrintReport().  

JavaScript Code 

Up Next
    Ebook Download
    View all
    Learn
    View all