Tech Talk : C# – Communication Between DHTML and C# AppThe following C# snippet demonstration how this can be done.


Required Windows controls

1) WebBrowser
2) Button

When the controls are added, this is what it should look like.

Xybernetics Communication Between Web Page and C Sharp


Code Overview

When the user clicks the C# application button (“C# App Button to Send Data to HTML”), the text message from the C# application (“Message from C#”) gets sent to the HTML webpage and the javascript (test() function in the webpage) displays a popup message using the alert() function.
When the user clicks the HTML button (“Message from HTML”), the text message from the HTML webpage (“Message from HTML”) gets sent to the C# application, and the MessageBox in the Test() function (in the C# application will display a popup with the HTML sent message.
Note that the HTML code is loaded into the WebBrowser control through the DocumentText property instead of being loaded from a separate HTML file.

using System;
using System.Windows.Forms;
using System.Security.Permissions;

namespace WindowsFormsApplication3
{
    [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.AllowWebBrowserDrop = false;
            webBrowser1.IsWebBrowserContextMenuEnabled = false;
            webBrowser1.WebBrowserShortcutsEnabled = false;
            webBrowser1.ObjectForScripting = this;
            // Uncomment the following line when you are finished debugging.
            //webBrowser1.ScriptErrorsSuppressed = true;

            webBrowser1.DocumentText =
                "" +
                "<button " + "onclick=\"window.external.Test('Message from HTML')\">" +
                "HTML Button to Send Data to C# App" +
                "";
        }
        public void Test(String message)
        {
            MessageBox.Show(message, "client code");
        }
        private void button2_Click(object sender, EventArgs e)
        {
            webBrowser1.Document.InvokeScript("test",
            new String[] { "Message from C#" });
        }
    }
}


Output

This is what you will get when you click the C# application button. That is the button with the “C# App Button to Send Data to HTML” text
Xybernetics Communication Between Web Page and C Sharp

This is what you get when you click on the HTML webpage button. Button with the text “” on it.
Xybernetics Communication Between Web Page and C Sharp


Reference