Use JavaScript Function in C# Windows Application

This article explains how to use a JavaScript function in a Windows application C#. In a previous article explained how to call a JavaScript function in C# code. The following are the points:

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

I have explained these points using an example. My example uses a WebBrowser control of a Windows Forms application.

Step 1: Initially create a new window based project. Execute Visual Studio then:

"File" -> "New" -> "Project..." then select "Windows" -> "Windows Forms Application".

Create new window project

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

Web Browser

Step 3: Then go to "Application" => "Add New Item" => "Add HTML page" to add a page to the debug folder of the application.

HTML page

Step 4: Create a JavaScript function in the HTML page. Here I need to write two functions, one function without a parameter and another one with a parameter.

javascript function

Step 5: Write this code in the Form Constructor.

Form Constructor

Step 6: Write this code for the Form Load event:

Form load method

Step 7: Write this code in the WebBrowser control's DocumentCompleted method.

browser control  Document
Step 8: Drag two Buttons and one TextBox control to your form. My form design now looks like this:

Form design

Step 9: After designing write this code for the button Click event.

code on button Click


When this Button is clicked you will get the following message:


The second button's output is:
Second Button Output