C # and Web JS intermodulation code

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.