现在的位置: 首页 > 综合 > 正文

NET中winform与webform互相通讯实例,CS调用BS页面的JS函数

2013年03月14日 ⁄ 综合 ⁄ 共 2091字 ⁄ 字号 评论关闭

大家都知道.NET可以开发winform与webform页面,有时候在开发项目过程中要结合BS+CS这样来应用,那么本站做一个实例来测试winform与webform互相通讯的实例,下面先看下效果:

winform调用bs页面的js函数效果图

 

 

webform页面发送信息到winform效果图

好了,看完上面的效果,下面我们看下如何实现吧。

第一、打开VS2008创建winform项目,之后在MainForm拖入浏览器控件,并命令这个浏览器控件名为:WebContainer

下面是全部CS端代码:

 /*
 *
 * 名称:CS与BS互相通讯
 * 作者:cc

 * 官方: http://www.cnblogs.com/chjun2000/ 
 */
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;

namespace TestJSWin
{
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            this.WebContainer.ObjectForScripting = this;   //这句很关键,主要和页面的JS互相操作
            Uri uriSale = new System.Uri("http://localhost:8012/index.htm"); //浏览器控件默认打开页面
            WebContainer.Url = uriSale;
        }

        /// <summary>
        /// 菜单点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void jsEventToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WebContainer.Navigate("javascript:fn_test();void(0);");
        }

        /// <summary>
        /// BS调用方法
        /// </summary>
        /// <param name="strShow"></param>
        public void JavascriptCall(string strShow)
        {
            MessageBox.Show(strShow);
        }
    }
}
好,做完winform,下面是http://localhost:8012/index.htm页面的做法。

 

第2、webform的页面,源码很简单,你可以直接复制源代码到本地测试就可以了。下面是HTML页面源代码:

 Code [http://www.xueit.com]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
    <head>
        <title>Test js event</title>
        <script language="javascript" type="text/javascript">
        <!--
            function fn_test() {
                alert("Hello, cs调用JS成功-学it网http://www.xueit.com/欢迎你");
            }

            function fn_call() {
                window.external.JavascriptCall("bs发送信息到winform成功");
            }
        -->
        </script>
    </head>
    <body>
    NET中winform与webform互相通讯实例-www.xueit.com(学IT网欢迎你访问)
    <input type="button" value="Call Winform Methed" onclick="fn_call()" />
    </body>
</html>
嗯!到现在为此,所有操作都可以了,非常简单,如果你有兴趣来按上面的代码来测试下

抱歉!评论已关闭.