WinForm与Javascript交互

来源:互联网 发布:网络视频直播方案 编辑:程序博客网 时间:2024/05/23 12:15

一、HTMLPage1.htm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Main Page</title>
<script type="text/javascript" language="javascript">
function  ShopXG(obj)
 {
    alert(obj);
 }

  function  InvokeFunc()
 {
     window.external.ShowMessage("呵呵");
 }
</script>

</head>

<body>
    <input type="button" id="aa" value="测试" onclick="InvokeFunc();"/>
</body>
</html>


二、创建一个WinForm应用程序,在应用程序窗体上添加一个浏览器控件:webBrowser1

添加一个button按钮。Button1用来测试调用JS事件


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Permissions;


namespace WindowsFormsApplication1
{
    //要想调用JS的类都需要添加一下两句  
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]  
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.webBrowser1.Url = new Uri(Application.StartupPath + @"\HTMLPage1.htm");
            webBrowser1.ObjectForScripting = this;    //这句是必不可少的,是调用JS的前提  
        }

        private void button1_Click(object sender, EventArgs e)
        {
            webBrowser1.Document.InvokeScript("ShopXG",new object[]{"这是WinForm调用JS的一个测试!"});  
        }

        public void ShowMessage(string message)  
        {  
            MessageBox.Show("这是JS调用的WinFormc程序的一个测试!");  
        }  
    }
}



原创粉丝点击