23
2015
11

C# WinForm与WebBrowser的页面交互

Webpage: Test.html

<html>
<head>
    <title>WebPageTest</title>
    <script type="text/javascript">
    function test()
       {
       alert("webJS函数");
       }
    </script>     
   </head>
   <body>
     <input type="button" id="test" value="test" onClick="test()">   
     <input type="button" name="callWinMethod" value="callWinMethod" onclick="window.external.winFormMethod('called from DHTML')">
   </body>
</html>


WinForm:

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

namespace WebBrowserTest
{
    //web访问winform
    [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]//[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]//  
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]//This property lets you integrate dynamic HTML (DHTML) code with your client application code
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            webBrowser1.Navigate(new Uri("file:///E:/AEE/Program_Test/Browser/Test.html"));
            webBrowser1.ObjectForScripting = this;//important
        }

        public void winFormMethod(string param)
        {
            MessageBox.Show(param);
        }

        //winform访问web的JS函数
        private void button1_Click(object sender, EventArgs e)
        {
            callJsMethod("test", "");
        }
        private void callJsMethod(string jsfun, string jsParameter)
        {
            HtmlDocument doc = webBrowser1.Document;
            doc.InvokeScript(jsfun, new object[] { jsParameter});
        }

    }
}


« 上一篇下一篇 »

相关文章:

关于空字符串比较的效率  (2015-11-13 17:16:52)

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。