winform 与 html 交互 简单案例(略加修改)

原文地址:http://www.cnblogs.com/zeroLove/p/3912460.html

一定要看到最后!!

本文主要简单的记录winform如何与html文件中的信息如何进行交互,即在winform中加载html界面,从而可以进行相互调用。

1.新建一个winform项目,若要在winform中加载html,需要一个webBrowser控件。

2.新建一个html页面,这里命名为“test.htm”.

3.c#代码:

复制代码

//为了使网页能够与winform交互 将com的可访问性设置为真
 [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
 [System.Runtime.InteropServices.ComVisibleAttribute(true)]

public void Hello()
{
    MessageBox.Show("OK,html在调用wf中的函数");
}

private void Form1_Load(object sender, EventArgs e)
{
    this.webBrowser1.ObjectForScripting = this;
    string path = Application.StartupPath + @"\test.htm";
    //MessageBox.Show(path);
    //this.webBrowser1.Navigate(path);
    this.webBrowser1.Url = new System.Uri(path, System.UriKind.Absolute);
}

复制代码

 

4.html代码:

复制代码

<html>
    <head>
        <title>this is a test</title>
        <script type ="text/javascript">
            function Hello() {
                 window.external.Hello();//getDebugPath()为c#方法
                //alert("hello");
             }
        </script>
    </head>
    <body>
        <button id="btn" οnclick="Hello()">hello</button>
    </body>
</html>

复制代码

 

5.结果:这里算是简单的完成了在winform中加载html,并在js中调用了c#中的信息。


 

6.为了方便,直接在上面的基础上实现在winform中调用html中的js函数。关键点:this.webBrowser1.Document.InvokeScript("js 的函数名", 参数");

 

7.c#代码:直接拖动一个button控件到页面中。

 

private void button1_Click(object sender, EventArgs e)
{
    this.webBrowser1.Document.InvokeScript("WfToHtml");
}

 

8.js代码:

<script type ="text/javascript">
    function WfToHtml() {
        alert("wf调用html里面的js函数");
    }
</script>

 

9.结果:

初学者,内容也比较简单,准备再加载一个swf,哈哈。。。

PS:这个例子运行时会抛出一个异常:

ObjectForScripting 的类必须对 COM 可见。请确认该对象是公共的,或考虑向您的类添加 ComVisible 属性。

解决方案:

添加引用

using System.Runtime.InteropServices;

在Form窗体类前添加

    [ComVisible(true)]
    public partial class Form1 : Form

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值