-
C#教程之WinForm项目开发中WebBrowser用法实例汇总
本文实例汇总了WinForm项目开发中WebBrowser用法,希望对大家项目开发中使用WebBrowser起到一定的帮助,具体用法如下:
1.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
[PermissionSet(SecurityAction.Demand, Name = "FullTrust" )] [ComVisibleAttribute( true )] public partial class frmWebData : Form { public frmWebData() { InitializeComponent(); } protected override void OnLoad(EventArgs e) { wbService.ObjectForScripting = this ; base .OnLoad(e); } } |
2.后台调用Javascript脚本
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<script type= "text/javascript" language= "javascript" > function ErrorMessage(message) { document.getElementById( "error" ).innerText = message; } </script> 后台代码 static string ErrorMsg = string .Empty; private void wbService_DocumentCompleted( object sender, WebBrowserDocumentCompletedEventArgs e) { if (! string .IsNullOrEmpty(ErrorMsg)) wbService.Document.InvokeScript( "ErrorMessage" , new object [1] { string .Format( "操作失败,原因:{0}!" , ErrorMsg) }); } |
3.JavaScript脚本调用后台方法
脚本代码
1
2
3
4
5
6
|
<div id= "content" > <h2 id= "error" > 操作正在响应中.....</h2> <div class= "utilities" > <a class= "button right" onclick= "window.external.DoSvrWebDbBack()" > |
刷新
1
2
3
4
5
6
7
|
</ a > <!--<a class="button right" onclick="window.external.NavigateToLogin()">重新登录</a>--> < div class = "clear" > </ div > </ div > </ div > |
后台代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public void DoSvrWebDbBack() { try { } catch (TimeoutException) { ErrorMsg = "超时,请稍候再尝试!" ; } catch (Exception ex) { ErrorMsg = ex.Message.ToString(); } } |
4.设置cookie
1
2
3
4
5
|
Cookie _cookie = BaseWinForm.LoginMessage.SessionID2; InternetSetCookie(BaseWinForm.LoginMessage.SvrWebDbBack, "ASP.NET_SessionId" , _cookie.Value); wbService.Navigate(BaseWinForm.LoginMessage.SvrWebDbBack, null , null , string .Format( "Referer:{0}" , BaseWinForm.LoginMessage.SvrWebDbLoingUrl)); [DllImport( "wininet.dll" , CharSet = CharSet.Auto, SetLastError = true )] public static extern bool InternetSetCookie( string urlName, string cookieName, string cookieData); |
5.请求链接获取返回处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
public class HttpWebRequestToolV2 { public delegate HttpWebRequest RequestRule( string url); /// <summary> /// 发起HttpWebResponse请求 /// </summary> /// <param name="url">请求连接</param> /// <param name="credentials">请求参数</param> /// <param name="httpWebRequestRule">请求设置『委托』,当委托等于NULL的时候,默认请求;否则使用所设置的HttpWebRequest</param> /// <returns>HttpWebResponse</returns> public static HttpWebResponse CreateHttpWebRequest( string url, byte [] credentials, RequestRule httpWebRequestRule) { if ( string .IsNullOrEmpty(url)) throw new ArgumentNullException( "url" ); HttpWebRequest _request = null ; if (httpWebRequestRule != null ) { _request = httpWebRequestRule(url); } else { _request = WebRequest.Create(url) as HttpWebRequest; _request.Method = "POST" ; _request.ContentType = "application/x-www-form-urlencoded" ; _request.CookieContainer = new CookieContainer(); } if (credentials != null ) { _request.ContentLength = credentials.Length; using (var requestStream = _request.GetRequestStream()) { requestStream.Write(credentials, 0, credentials.Length); } } return _request.GetResponse() as HttpWebResponse; } /// <summary> /// 创建验证凭证 /// eg: /// IDictionary<string, string> _requestCredentials = new Dictionary<string, string>(); ///_requestCredentials.Add("UserName", _userName); ///_requestCredentials.Add("PassWord", _userPwd); ///_requestCredentials.Add("MacAddress", _macAddress); ///byte[] _credentials = HttpWebRequestToolV2.CreateCredentials(_requestCredentials, Encoding.UTF8); /// </summary> /// <returns></returns> public static byte [] CreateCredentials(IDictionary< string , string > credentials, Encoding encoding) { if (credentials == null ) throw new ArgumentNullException( "credentials" ); if (credentials.Count == 0) throw new ArgumentException( "credentials" ); if (encoding == null ) throw new ArgumentNullException( "encoding" ); StringBuilder _credentials = new StringBuilder(); foreach (KeyValuePair< string , string > credential in credentials) { _credentials.AppendFormat( "{0}={1}&" , credential.Key, credential.Value); } string _credentialsString = _credentials.ToString().Trim(); int _endIndex = _credentialsString.LastIndexOf( '&' ); if (_endIndex != -1) _credentialsString = _credentialsString.Substring(0, _endIndex); return encoding.GetBytes(_credentialsString); } |
使用示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
public static HttpWebRequest RequestSetting( string url) { HttpWebRequest _request = null ; _request = WebRequest.Create(url) as HttpWebRequest; _request.Method = "POST" ; _request.ContentType = "application/x-www-form-urlencoded" ; _request.Timeout = 1000 * 10; //超时五秒 _request.CookieContainer = new CookieContainer(); return _request; } /// <summary> /// 登录web网页验证 /// </summary> /// <param name="url">超链接</param> /// <param name="_userName">用户名</param> /// <param name="_userPwd">密码</param> /// <param name="_macAddress">MAC地址</param> /// <param name="sessionID">会话</param> /// <returns>网页登录验证是否成功『失败,将抛出网页验证验证失败信息』</returns> public bool ProcessRemoteLogin( string url, string _userName, string _userPwd, string _macAddress, out Cookie sessionID) { bool _checkResult = false ; string _errorMessage = string .Empty; //--------------------创建登录凭证-------------------- IDictionary< string , string > _requestCredentials = new Dictionary< string , string >(); _requestCredentials.Add( "UserName" , _userName); _requestCredentials.Add( "PassWord" , _userPwd); _requestCredentials.Add( "MacAddress" , _macAddress); byte [] _credentials = HttpWebRequestToolV2. CreateCredentials (_requestCredentials, Encoding.UTF8); //----------------------------------------------------- CookieCollection _cookie = null ; /* *LoginType 1:成功 0:失败 *Err 失败原因 */ using (HttpWebResponse _httpRespone = HttpWebRequestToolV2. CreateHttpWebRequest (url, _credentials, RequestSetting)) { _cookie = new CookieCollection(); if (_httpRespone.Cookies.Count > 0) _cookie.Add(_httpRespone.Cookies); } //------------------------------------------------------- Cookie _loginType = _cookie[ "LoginType" ]; sessionID = _cookie[ "ASP.NET_SessionId" ]; Cookie _err = _cookie[ "Err" ]; if (_loginType != null && _err != null && sessionID != null ) { _checkResult = _loginType.Value.Equals( "1" ); if (!_checkResult) _errorMessage = HttpUtility.UrlDecode(_err.Value); } else { _errorMessage = "Web服务异常,请稍候在试!" ; } if (! string .IsNullOrEmpty(_errorMessage)) throw new Exception(_errorMessage); return _checkResult; } |
6.从WebBrowser中获取CookieContainer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
/// <summary> /// 从WebBrowser中获取CookieContainer /// </summary> /// <param name="webBrowser">WebBrowser对象</param> /// <returns>CookieContainer</returns> public static CookieContainer GetCookieContainer( this WebBrowser webBrowser) { if (webBrowser == null ) throw new ArgumentNullException( "webBrowser" ); CookieContainer _cookieContainer = new CookieContainer(); string _cookieString = webBrowser.Document.Cookie; if ( string .IsNullOrEmpty(_cookieString)) return _cookieContainer; string [] _cookies = _cookieString.Split( ';' ); if (_cookies == null ) return _cookieContainer; foreach ( string cookieString in _cookies) { string [] _cookieNameValue = cookieString.Split( '=' ); if (_cookieNameValue.Length != 2) continue ; Cookie _cookie = new Cookie(_cookieNameValue[0].Trim().ToString(), _cookieNameValue[1].Trim().ToString()); _cookieContainer.Add(_cookie); } return _cookieContainer; } |
栏目列表
最新更新
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
Python初学者友好丨详解参数传递类型
如何有效管理爬虫流量?
SQL SERVER中递归
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比
一款纯 JS 实现的轻量化图片编辑器
关于开发 VS Code 插件遇到的 workbench.scm.
前端设计模式——观察者模式
前端设计模式——中介者模式
创建型-原型模式