程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> WinForm項目開辟中WebBrowser用法實例匯總

WinForm項目開辟中WebBrowser用法實例匯總

編輯:C#入門知識

WinForm項目開辟中WebBrowser用法實例匯總。本站提示廣大學習愛好者:(WinForm項目開辟中WebBrowser用法實例匯總)文章只能為提供參考,不一定能成為您想要的結果。以下是WinForm項目開辟中WebBrowser用法實例匯總正文


本文實例匯總了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;
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved