WebBrowser 控件可以让你装载Windows Form 应用程序中的 Web 网页和其它采用浏览器的文件。可以使用webbrowser 控件将现有的web框架控制项加入至 Windows Form 客户端应用程序。
还是直接看代码吧。

WebBrowser 控制项 提供的属性、方法和事件,可用来实现 Internet Explorer 的控制项
    webBrowser1.Navigate("www.cnblogs.com");    //将指定位置处的文件载入至 WebBrowser
    webBrowser1.GoBack();//上一页
    webBrowser1.GoForward();//下一页
    webBrowser1.Refresh();//刷新
    webBrowser1.GoHome();//主页
这里提供了WebBrowser常用的方法,

上面的代码是将 我们园子的主页载入到WebBrowser控件中。如果我们想要在应用程式中产生自己的网页内容,可以设定DocumentText属性。也可以通过Document属性来处理目前的网页内容。如下代码是使用 DocumentText 属性,显示网页内容。并用Document属性来处理所显示的网页。

 1private void btnDocumentText_Click(object sender, EventArgs e)
 2        {
 3            string szHtml = @"
 4<HTML>
 5<HEAD>
 6<TITLE> DocumentText </TITLE>
 7</HEAD>
 8
 9<BODY>
10     Please enter your name:<br/>
11     <input type='text' name='Name'/><br/>
12    <a href='http://www.microsoft.com' >Send input to method of Form class</a>
13     
14</BODY>
15</HTML>";
16
17            webBrowser1.DocumentText = szHtml;
18          
19        }
20
21        private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
22        {
23            System.Windows.Forms.HtmlDocument document =  this.webBrowser1.Document;
24
25            if (document != null && document.All["Name"] != null && String.IsNullOrEmpty(document.All["Name"].GetAttribute("value")))
26            {
27                e.Cancel = true;
28                System.Windows.Forms.MessageBox.Show("You must enter your name before you can navigate to " +  e.Url.ToString());
29            }
30
31        }

既然我们可以通过DocumentText生成自己的网页,那么能不能象使用IE那样操作这个网页呢?,答案是肯定的,完全可以像操作Web程序那样操作WebBrowser 控制项。比如我们可以加入脚本,CSS。当然,如果你熟悉 HTML 物件对象模型 (DOM),也可以透过 Document 属性来处理目前的Web网页内容。下面的例子加入了JavaScript脚本来控制网页。如果要在Winfrom程序中写大量的Javascriot代码,而且这些代码最终要转换成String型载入到Webbrowser 那将是很痛苦的事情,不过没有关系,我们可以创建一个js文件,放入资源中,用的时候只需从资源中载入即可。这里我创建一个名为 ClientScript.js 的文件。

 1<script language = "javascript">
 2function ClickEvent(name)
 3{
 4    alert("Hello: " +name);
 5}
 6
 7function KeyDown()
 8
 9    if (event.keyCode==116)
10    {
11         event.keyCode=0;
12         event.returnValue=false;
13    }
14  
15      return false;
16}
string szClientScript = ManagedWebBrowser.Properties.Resources.ResourceManager.GetString("ClientScript");

            string szWebBrowserText = "<html>" +
                "<head>" +
                "<title></title>"+                
                    szClientScript +
                 "</head>" +
               "<body onkeydown=\"KeyDown()\" oncontextmenu=\"event.returnValue=false\">"+
               
               "Please enter your name:<br/>"+
                 "<input type='text' name='Name'/><br/>"+
                 "<font onclick = 'ClickEvent(Name.value)'>Click Here</font>"+
                "</body></html>";


            webBrowser1.DocumentText = szWebBrowserText;

WebBrowser 是 System.Windows.Forms 下的控制项,也就是意味着它是用在WimForm程序下,那么WebWrower所载入的Web页面如何实现在WinForm程序下处理呢。例如上例中的 "<font onclick = 'ClickEvent(Name.value)'>Click Here</font>" 。这里的Click事件是通过脚本处理的,如何让这个Click事件在Winform中处理呢?这里要做一些修改。若要从指令码存取用户端应用程式,需要设定ObjectForScripting 属性。指令码可以将您指定的物件当做window.external 物件来存取。

使用ObjectForScripting属性,可启用 WebBrowser 控制项所装载之 Web 网页与包含 WebBrowser 控制项之应用程式间的通讯。
这个属性可让您整合动态超文字标记语言 (DHTML) 程式码与用户端应用程式程式码。
指定给这个属性的物件可让 Web 网页指令码做为 window.external 物件,这个物件是为了存取主应用程式而提供的内建 DOM 物件。

 1 private void btnScriptEvent_Click(object sender, EventArgs e)
 2        {
 3
 4            // This is the handler for loading the script into the Web Browser control and allowing us to interact
 5            // between the script in the Browser control and this form class
 6
 7
 8            // Set the ObjectForScripting property of the Web Browser control to point to this form class
 9            // This will allow us to interact with methods in this form class via the window.external property 
10            webBrowser1.ObjectForScripting = this;
11
12            string szWebBrowserText = "<html>" +
13                "<head>" +
14                "<title></title>"+                    
15                 "</head>" +
16               "<body onkeydown=\"KeyDown()\" oncontextmenu=\"event.returnValue=false\">"+
17               
18               "Please enter your name:<br/>"+
19                 "<input type='text' name='Name'/><br/>"+
20                 "<font onClick='window.external.ClickEvent(Name.value)'>Click Here</font>"+
21                "</body></html>";
22
23
24            webBrowser1.DocumentText = szWebBrowserText;
25        }
26        public void ClickEvent(string userName)
27        {
28            // Simply echo out the name that the user typed in the input box of the HTML page
29            if (System.Threading.Thread.CurrentThread.CurrentUICulture.TextInfo.IsRightToLeft == true)
30                MessageBox.Show("Hello " + userName, "Managed Web Browser Sample", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading);
31            else
32                MessageBox.Show("Hello " + userName, "Managed Web Browser Sample", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
33
34        }

这里的ObjectForScripting 属性设置为 this。注意:在From1 类的开头加入了这么一句[ComVisible(true)], 它在System.Runtime.InteropServices下,预设值为 true,指出 Managed 型别对于 COM 为可见的。

[ComVisible(true)]
 public partial class Form1 : System.Windows.Forms.Form

webbrowser 控件实现WinForm与WebForm交互的更多相关文章

  1. 浏览器自动化的一些体会5 webBrowser控件之winform和webBrowser的交互

    从winform访问webBrowser,大致就是利用webBrowser提供的解析dom的方法以及用InvokeScript方法执行javascript.这个相对比较简单. 从webBrowser访 ...

  2. webBrower控件实现winform和webpage交互

    添加WebBrowser控件 private WebBrowser webBrowser1; 引用页面的document对象 HtmlDocument doc = webBrowser1.Docume ...

  3. c#: WebBrowser控件html代码注入及交互

    主题仍是下载相关. 页面加载完成后,注入html元素,以使能够与主程序交互.并使WebBrowser与js交互,可以实现一些有趣的功能. 欲使WebBrowser与js交互,其所在页面类,须加上[Co ...

  4. .Net2.0 --Winform结合WebBrowser控件和Socket老技术来实现另类Push~

    原文:.Net2.0 --Winform结合WebBrowser控件和Socket老技术来实现另类Push~ 目前的企业级开发比较流行的是Web2.0技术,但是由于Web技术基于请求--响应的交互模式 ...

  5. WinForm webbrowser控件的使用

    webbrowser是一个比较实用的工具,主要用于在winform窗体中嵌入浏览器,达到winform与webform互操作的目的. 先上一个demo,看一下能实现什么效果. private void ...

  6. C# Winform WebBrowser控件

    C# WinForm WebBrowser 1.主要用途:使用户可以在窗体中导航网页. 2.注意:WebBrowser 控件会占用大量资源.使用完该控件后一定要调用 Dispose 方法,以便确保及时 ...

  7. Winform中修改WebBrowser控件User-Agent的方法(已经测试成功)

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.W ...

  8. WPF中嵌入WinForm中的webbrowser控件

    原文:WPF中嵌入WinForm中的webbrowser控件 使用VS2008创建WPF应用程序,需使用webbrowser.从工具箱中添加WPF组件中的webbrowser发现其中有很多属性事件不能 ...

  9. winform WebBrowser控件中,cs后台代码执行动态生成的js

    很多文章都是好介绍C# 后台cs和js如何交互,cs调用js方法(js方法必须是页面上存在的,已经定义好的),js调用cs方法, 但如果想用cs里面执行动态生成的js代码,如何实现呢? 思路大致是这样 ...

随机推荐

  1. To discount or not to discount in reinforcement learning: A case study comparing R learning and Q learning

    https://www.cs.cmu.edu/afs/cs/project/jair/pub/volume4/kaelbling96a-html/node26.html [平均-打折奖励] Schwa ...

  2. 【题解】Painting Fence

    [题解]Painting Fence 分治模板.贪心加分治.直接\(O(n^2logn)\)分治过去.考虑一块联通的柱形是子问题的,是递归的,贪心分治就可.记得对\(r-l+1\)取\(min\). ...

  3. 在RedHat Linux系统中安装和配置snmp服务

    检查系统是否安装snmp服务 # rpm -qa|grep snmp net-snmp-5.3.2.2-17.el5 net-snmp-perl-5.3.2.2-17.el5 net-snmp-dev ...

  4. 各种python 函数參数定义和解析

    python 中的函数參数是赋值式的传递的,函数的使用中要注意两个方面:1.函数參数的定义过程,2.函数參数在调用过程中是怎样解析的. 首先说一下在python 中的函数调用过程是分四种方式的.这里且 ...

  5. 在maven 中部署SSM项目找不 Spring ContextLoaderListener 的解决办法

    1.项目使用技术:maven的项目使用了Spring MVC+Spring +Mybatis+Tomcat搭建一个项目. 2.报错信息: Error configuring application l ...

  6. HDU - 1260 Tickets 【DP】

    题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1260 题意 有N个人来买电影票 因为售票机的限制 可以同时 卖一张票 也可以同时卖两张 卖两张的话 两 ...

  7. 5.1 《锋利的jQuery》jQuery对表单的操作

    获取焦点和失去焦点改变样式 改变文本框/滚动条高度 复选框应用 下拉框应用 表单验证 tip1: 注意使用<label>的for标签,对应input的id.(for 属性规定 label ...

  8. CentOS已经安装命令,但提示找不到

    今天在虚机上装了个CENTOS.装好后,好多命令都提示找不到,如tcpdump.arp.ifconfig.查看安装包,都已经安装过. ------------无敌分割线------------- # ...

  9. POJ2104 K-th Number (子区间内第k大的数字)【划分树算法模板应用】

    K-th Number Time Limit: 20000MS   Memory Limit: 65536K Total Submissions: 40920   Accepted: 13367 Ca ...

  10. springboot简单介绍

    1.springboot简单介绍 微服务架构 Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程. 该框架使用了特定的方 ...