在winfrom中使用webBrowser webBrowser 中C#方法和JS方法的互相调用

1.在webBrowser使用过程中为了C#和JS通讯,webBrowser必须设置ObjectForScripting的属性,它是一个object,这个object可以提供给webBrowser控件载入的网页上的script访问。

    在设置过webBrowser控件的ObjectForScripting属性后,还需要设置应用程序对com可见,不然会抛出一个异常(ObjectForScripting 的类必须对 COM 可见。请确认该对象是公共的,或考虑向您的类添加 ComVisible 属性。),可做如下设置:

[System.Runtime.InteropServices.ComVisible(true)]  把这个标签添加到相应的类中

事例: 这是工程一  Form1中添加了webBrowser

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Windows.Forms;
 9 using System.Runtime.InteropServices;
10 namespace 测试1
11 {
12     [ComVisible(true)]
13     public partial class Form1 : Form
14     {
15         public Form1()
16         {
17             InitializeComponent();
18         }
19         protected override void OnLoad(EventArgs e)
20         {
21             webBrowser1.ObjectForScripting = this;
22             webBrowser1.Navigate("http://localhost:57440/test.aspx");
23              base.OnLoad(e);
24         }
25         /// <summary>
26         /// 这个方法是提供给JS 调用的,
27         /// </summary>
28         /// <param name="str"></param>
29         /// <param name="i"></param>
30         public void Test(string str,int i)
31         {  //显示一个MBOX  为了证明已经执行了C#方法
32             MessageBox.Show("<script>alert("+str+":"+i+")</script>");
33            //这里是C# 代码调用JS的代码
34             webBrowser1.Document.InvokeScript("test",new Object[]{1,"hello"});
35             //C#代码产生一个新窗体 为了证明已经执行了C#方法
36             //Form2 f = new Form2("我设置了info1");
37             //f.Show();
38         }
39     }
40 }


事例:这是工程二  新建一个项目添加一个页面, "http://localhost:57440/test.aspx"是这个页面的URL

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="BusinessBookWebData.test" %>
 2 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4 <html xmlns="http://www.w3.org/1999/xhtml">
 5 <head runat="server">
 6     <title></title>
 7 </head>
 8 <body>
 9     <script type="text/javascript">        //提供给c#调用的方法    
10         function test(n, s) {
11             alert(n + "/" + s);
12         }     //调用C#的方法     
13         function callCSharp() {         //这里可以看到window.external被设置成了什么        
14             alert(window.external);
15             window.external.Test("我是js:", 15);
16            
17         } 
18     </script>
19     <button onclick="callCSharp()">
20         call c#</button>
21 </body>
22 </html>


总结:单击 “call C#”  按钮时 通过  window.external.Test("我是js:", 15); 执行 C#的Test方法,在C#的方法中又调用了JS的方法。

具体效果最好自己去实现。

同过这个小测试实现了C# 和JS方法的互相调用。

注本文参考:http://www.cnblogs.com/JuneZhang/archive/2012/11/10/2763773.html

原文地址:https://www.cnblogs.com/liuyu7177/p/3040264.html