当前位置:  编程技术>.net/c#/asp.net

WinForm项目开发中WebBrowser用法实例汇总

    来源: 互联网  发布时间:2014-11-01

    本文导语:  本文实例汇总了WinForm项目开发中WebBrowser用法,希望对大家项目开发中使用WebBrowser起到一定的帮助,具体用法如下: 1. [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] [ComVisibleAttribute(true)] public partial class frmWebData : Form { public...

本文实例汇总了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脚本


function ErrorMessage(message) {
  document.getElementById("error").innerText = message;
}

后台代码

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脚本调用后台方法

脚本代码

  
操作正在响应中.....

刷新

后台代码

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);
/// 
/// 发起HttpWebResponse请求
/// 
/// 请求连接
/// 请求参数
/// 请求设置『委托』,当委托等于NULL的时候,默认请求;否则使用所设置的HttpWebRequest
/// HttpWebResponse
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;
}

/// 
/// 创建验证凭证
/// eg:
/// IDictionary _requestCredentials = new Dictionary();
///_requestCredentials.Add("UserName", _userName);
///_requestCredentials.Add("PassWord", _userPwd);
///_requestCredentials.Add("MacAddress", _macAddress);
///byte[] _credentials = HttpWebRequestToolV2.CreateCredentials(_requestCredentials, Encoding.UTF8);
/// 
/// 
public static byte[] CreateCredentials(IDictionary 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 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;
}

/// 
/// 登录web网页验证
/// 
/// 超链接
/// 用户名
/// 密码
/// MAC地址
/// 会话
/// 网页登录验证是否成功『失败,将抛出网页验证验证失败信息』
public bool ProcessRemoteLogin(string url, string _userName, string _userPwd, string _macAddress, out Cookie sessionID)
{

  bool _checkResult = false;
  string _errorMessage = string.Empty;
  //--------------------创建登录凭证--------------------
  IDictionary _requestCredentials = new Dictionary();
  _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

/// 
/// 从WebBrowser中获取CookieContainer
/// 
/// WebBrowser对象
/// CookieContainer
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;
}

    
 
 

您可能感兴趣的文章:

  • WinForm项目开发中NPOI用法实例解析
  • WinForm项目开发中Excel用法实例解析
  •  
    本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • WinForm开发中屏蔽WebBrowser脚本错误提示的方法
  • C#之WinForm WebBrowser实用技巧汇总
  • c#多线程更新窗口(winform)GUI的数据
  • .Net WInform开发笔记(二)Winform程序运行结构图及TCP协议在Winform中的应用
  • C# WinForm中禁止改变窗口大小的方法
  • WinForm相对路径的陷阱
  • c# Winform 全窗口拖动的代码
  • Winform实现抓取web页面内容的方法
  • WinForm实现关闭按钮不可用或隐藏的方法
  • 解读在C#中winform程序响应键盘事件的详解
  • c# winform 关闭窗体时同时结束线程实现思路
  • WinForm实现读取Resource中文件的方法
  • C# Winform 整个窗口拖动的实现代码
  • WinForm下 TextBox只允许输入数字的小例子
  • Winform跨线程操作的简单方法
  • C# WinForm程序完全退出的问题解决
  • C# WinForm窗体编程中处理数字的正确操作方法
  • C# Winform 让整个窗口都可以拖动
  • 使用C# Winform应用程序获取网页源文件的解决方法
  • c# 天气预报查询(winform方法)的实现代码(图文)
  • C# Winform 禁止用户调整ListView的列宽
  • C# winform编程中响应回车键的实现代码
  • C#中禁止Winform窗体关闭的实现方法


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3