C # and Web JS intermodulation code
1, first write a page in the main program directory: test.html
<!DOCTYPE HTML><HTMLLang= "en"xmlns= "http://www.w3.org/1999/xhtml"><Head> <MetaCharSet= "Utf-8" /> <title>Test Web page</title> <Script> functionMyFunc (num) {alert ("Hello everyone, this is the JS code alert, I will return 30! "); return - +num; } </Script></Head><Body> <inputtype= "button"onclick= "Window.external.MyMessageBox (' JavaScript accesses C # code ');"value= "Click Test to call Methods in C #!" " /></Body></HTML>
2, open WinForm, drag a button, drag a webbrowser.
3. Write C # code and test
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;namespacewebwithform{[System.Runtime.InteropServices.ComVisible (true)] Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); This. webbrowser2.objectforscripting = This; } Private voidForm1_Load (Objectsender, EventArgs e) { This. webbrowser2.navigate (Application.startuppath +"\\test.html"); } Private voidButton1_Click (Objectsender, EventArgs e) { varresult = This. WebBrowser2.Document.InvokeScript ("MyFunc",New Object[] { - }); This. Text = This. webBrowser2.Version.ToString (); Label1. Text="Web page return:"+result; } Public voidMymessagebox (stringmessage) {MessageBox.Show ("This is the MessageBox hint for C #:"+message); } }}
4. Operation Effect:
C # and Web JS intermodulation code