欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

WinForm項(xiàng)目開發(fā)中WebBrowser用法實(shí)例匯總

 更新時(shí)間:2014年08月07日 09:07:17   投稿:shichen2014  
這篇文章主要介紹了WinForm項(xiàng)目開發(fā)中WebBrowser用法,需要的朋友可以參考下

本文實(shí)例匯總了WinForm項(xiàng)目開發(fā)中WebBrowser用法,希望對大家項(xiàng)目開發(fā)中使用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.后臺調(diào)用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腳本調(diào)用后臺方法

腳本代碼

  <div id="content">
 <h2 id="error">
   操作正在響應(yīng)中.....</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 = "超時(shí),請稍候再嘗試!";
  }
  catch (Exception ex)
  {
 ErrorMsg = ex.Message.ToString();
  }
}

4.設(shè)置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>
/// 發(fā)起HttpWebResponse請求
/// </summary>
/// <param name="url">請求連接</param>
/// <param name="credentials">請求參數(shù)</param>
/// <param name="httpWebRequestRule">請求設(shè)置『委托』,當(dāng)委托等于NULL的時(shí)候,默認(rèn)請求;否則使用所設(shè)置的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>
/// 創(chuàng)建驗(yàn)證憑證
/// 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;//超時(shí)五秒
  _request.CookieContainer = new CookieContainer();
  return _request;
}

/// <summary>
/// 登錄web網(wǎng)頁驗(yàn)證
/// </summary>
/// <param name="url">超鏈接</param>
/// <param name="_userName">用戶名</param>
/// <param name="_userPwd">密碼</param>
/// <param name="_macAddress">MAC地址</param>
/// <param name="sessionID">會話</param>
/// <returns>網(wǎng)頁登錄驗(yàn)證是否成功『失敗,將拋出網(wǎng)頁驗(yàn)證驗(yàn)證失敗信息』</returns>
public bool ProcessRemoteLogin(string url, string _userName, string _userPwd, string _macAddress, out Cookie sessionID)
{

  bool _checkResult = false;
  string _errorMessage = string.Empty;
  //--------------------創(chuàng)建登錄憑證--------------------
  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服務(wù)異常,請稍候在試!";
  }
  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;
}

相關(guān)文章

  • C#使用yield關(guān)鍵字構(gòu)建迭代器詳解

    C#使用yield關(guān)鍵字構(gòu)建迭代器詳解

    這篇文章主要為大家詳細(xì)介紹了C#使用yield關(guān)鍵字構(gòu)建迭代器的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-10-10
  • 深入分析C# 線程同步

    深入分析C# 線程同步

    這篇文章主要介紹了C# 線程同步的的相關(guān)資料,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-06-06
  • C#結(jié)合OpenCVSharp4實(shí)現(xiàn)圖片相似度識別

    C#結(jié)合OpenCVSharp4實(shí)現(xiàn)圖片相似度識別

    這篇文章主要為大家詳細(xì)介紹了C#如何結(jié)合OpenCVSharp4實(shí)現(xiàn)圖片相似度識別,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下
    2023-09-09
  • C#中GraphicsPath的Flatten方法用法實(shí)例

    C#中GraphicsPath的Flatten方法用法實(shí)例

    這篇文章主要介紹了C#中GraphicsPath的Flatten方法,實(shí)例分析了Flatten方法的相關(guān)使用技巧,需要的朋友可以參考下
    2015-06-06
  • C#中使用Spire.doc對word的操作方式

    C#中使用Spire.doc對word的操作方式

    這篇文章主要介紹了C#中使用Spire.doc對word的操作方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-01-01
  • C#排序算法之歸并排序

    C#排序算法之歸并排序

    這篇文章主要為大家詳細(xì)介紹了C#排序算法之歸并排序,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-01-01
  • 詳解c#與python的交互方式

    詳解c#與python的交互方式

    這篇文章主要介紹了詳解c#與python的交互方式,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下
    2021-04-04
  • C#創(chuàng)建及訪問網(wǎng)絡(luò)硬盤的實(shí)現(xiàn)

    C#創(chuàng)建及訪問網(wǎng)絡(luò)硬盤的實(shí)現(xiàn)

    本文主要介紹了C#創(chuàng)建及訪問網(wǎng)絡(luò)硬盤的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • C#四種計(jì)時(shí)器Timer的區(qū)別和用法

    C#四種計(jì)時(shí)器Timer的區(qū)別和用法

    這篇文章介紹了C#四種計(jì)時(shí)器Timer的區(qū)別和用法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-05-05
  • utf8編碼檢測方法分享

    utf8編碼檢測方法分享

    這篇文章主要介紹了utf8編碼檢測方法示例,需要的朋友可以參考下
    2014-02-02

最新評論