WinForm项目开发中WebBrowser用法实例汇总
更新时间:2020年6月25日 11:35 点击:1700
本文实例汇总了WinForm项目开发中WebBrowser用法,希望对大家项目开发中使用WebBrowser起到一定的帮助,具体用法如下:
1.
[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脚本
<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脚本调用后台方法
脚本代码
<div id="content"> <h2 id="error"> 操作正在响应中.....</h2> <div class="utilities"> <a class="button right" onclick="window.external.DoSvrWebDbBack()">
刷新
</a> <!--<a class="button right" onclick="window.external.NavigateToLogin()">重新登录</a>--> <div class="clear"> </div> </div> </div>
后台代码
public void DoSvrWebDbBack() { try { } catch (TimeoutException) { ErrorMsg = "超时,请稍候再尝试!"; } catch (Exception ex) { ErrorMsg = ex.Message.ToString(); } }
4.设置cookie
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.请求链接获取返回处理
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); }
使用示例
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
/// <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; }
相关文章
- 本篇文章是对C#中WinForm控件之Dock顺序调整进行了详细的分析介绍,需要的朋友参考下...2020-06-25
- 这篇文章主要介绍了C# Winform中实现主窗口打开登录窗口关闭的方法,这在需要用户名密码的软件项目中是必用的一个技巧,要的朋友可以参考下...2020-06-25
- 下面小编就为大家带来一篇C# winform打开Excel文档的方法总结(必看篇)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
- 这篇文章主要给大家介绍C# winform快捷键设置技巧,涉及到C winform快捷键相关知识,对C winform知识感兴趣的朋友可以参考下本篇文章...2020-06-25
c#中Winform实现多线程异步更新UI(进度及状态信息)
本篇文章主要介绍了c#中Winform实现多线程异步更新UI(进度及状态信息) ,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25- 这篇文章主要给大家介绍了关于c# winform异步不卡界面的实现方法,文中通过示例代码介绍的非常详细,对大家学习或者使用c#具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧...2020-06-25
C# WinForm程序处理后台繁忙导致前台控件假死现象解决方法
这篇文章主要介绍了C# WinForm程序处理后台繁忙导致前台控件假死现象解决方法,本文通过Application.DoEvents()解决这个问题,并讲解了Application.DoEvents()的作用,需要的朋友可以参考下...2020-06-25- 这篇文章主要介绍了C#中winform使用相对路径读取文件的方法,实例分析了C#使用相对路径读取文件的技巧与实际应用,需要的朋友可以参考下...2020-06-25
- 这篇文章主要介绍了C#中WebBroeser控件用法,包括了常用属性、事件处理及应用实例,需要的朋友可以参考下...2020-06-25
winform中的ListBox和ComboBox绑定数据用法实例
这篇文章主要介绍了winform中的ListBox和ComboBox绑定数据用法,实例分析了将集合数据绑定到ListBox和ComboBox控件的技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25- 这篇文章主要介绍了C#在Winform开发中使用Grid++报表,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
- 这篇文章主要为大家详细介绍了C# WinForm程序设计简单计算器,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-06-25
C# WinForm控件对透明图片重叠时出现图片不透明的简单解决方法
这篇文章主要介绍了C# WinForm控件对透明图片重叠时出现图片不透明的简单解决方法,结合实例形式分析了WinForm图片重叠后造成图片不透明的原因与相应的解决方法,需要的朋友可以参考下...2020-06-25C# 使用 WebBrowser 实现 HTML 转图片功能的示例代码
这篇文章主要介绍了C# 如何使用 WebBrowser 实现 HTML 转图片功能,文中示例代码非常详细,帮助大家更好的理解和学习,感兴趣的朋友可以了解下...2020-11-03- 在工作中遇到这样一个问题,在系统使用过程中,输入法会变灰导致无法使用输入法输入文字,就好像输入法被禁用了没有启用似的。对此,在这里做个备录...2020-06-25
- 这篇文章主要介绍了C#实现Winform中打开网页页面的方法,涉及WinForm中WebBrowser的相关使用技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
C#实现winform中RichTextBox在指定光标位置插入图片的方法
这篇文章主要介绍了C#实现winform中RichTextBox在指定光标位置插入图片的方法,涉及RichTextBox控件及剪切板的相关操作技巧,非常简单实用,需要的朋友可以参考下...2020-06-25C# Winform 调用系统接口操作 INI 配置文件的代码
封装了一小段代码, 调用系统接口, 操作配置文件. 一般用于 .ini 文件, 或者其它键值对格式的配置文件...2020-06-25- 这篇文章主要介绍了WinForm调用百度地图接口用法,结合具体实例形式简单分析了WinForm WebBrower控件与前端百度接口交互的相关操作技巧,需要的朋友可以参考下...2020-06-25
- 在.NET应用中,导出Excel是很常见的需求,导出Excel报表大致有以下三种方式:Office PIA,文件流和NPOI开源库,本文只介绍前两种方式...2020-06-25