WinForm項(xiàng)目開(kāi)發(fā)中WebBrowser用法實(shí)例匯總
本文實(shí)例匯總了WinForm項(xiàng)目開(kāi)發(fā)中WebBrowser用法,希望對(duì)大家項(xiàng)目開(kāi)發(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.后臺(tái)調(diào)用Javascript腳本
<script type="text/javascript" language="javascript">
function ErrorMessage(message) {
document.getElementById("error").innerText = message;
}
</script>
后臺(tái)代碼
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)用后臺(tái)方法
腳本代碼
<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>
后臺(tái)代碼
public void DoSvrWebDbBack()
{
try
{
}
catch (TimeoutException)
{
ErrorMsg = "超時(shí),請(qǐng)稍候再嘗試!";
}
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.請(qǐng)求鏈接獲取返回處理
public class HttpWebRequestToolV2
{
public delegate HttpWebRequest RequestRule(string url);
/// <summary>
/// 發(fā)起HttpWebResponse請(qǐng)求
/// </summary>
/// <param name="url">請(qǐng)求連接</param>
/// <param name="credentials">請(qǐng)求參數(shù)</param>
/// <param name="httpWebRequestRule">請(qǐng)求設(shè)置『委托』,當(dāng)委托等于NULL的時(shí)候,默認(rèn)請(qǐng)求;否則使用所設(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è)驗(yàn)證
/// </summary>
/// <param name="url">超鏈接</param>
/// <param name="_userName">用戶名</param>
/// <param name="_userPwd">密碼</param>
/// <param name="_macAddress">MAC地址</param>
/// <param name="sessionID">會(huì)話</param>
/// <returns>網(wǎng)頁(yè)登錄驗(yàn)證是否成功『失敗,將拋出網(wǎng)頁(yè)驗(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ù)異常,請(qǐng)稍候在試!";
}
if (!string.IsNullOrEmpty(_errorMessage))
throw new Exception(_errorMessage);
return _checkResult;
}
6.從WebBrowser中獲取CookieContainer
/// <summary>
/// 從WebBrowser中獲取CookieContainer
/// </summary>
/// <param name="webBrowser">WebBrowser對(duì)象</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;
}
- WinForm窗體間傳值的方法
- C#,winform,ShowDialog,子窗體向父窗體傳值
- WinForm項(xiàng)目開(kāi)發(fā)中Excel用法實(shí)例解析
- WinForm項(xiàng)目開(kāi)發(fā)中NPOI用法實(shí)例解析
- Winform基于多線程實(shí)現(xiàn)每隔1分鐘執(zhí)行一段代碼
- C#之WinForm跨線程訪問(wèn)控件實(shí)例
- WinForm實(shí)現(xiàn)攔截窗體上各個(gè)部位的點(diǎn)擊特效實(shí)例
- WinForm的延時(shí)加載控件概述
- Winform啟動(dòng)另一個(gè)項(xiàng)目傳值的方法
相關(guān)文章
C#實(shí)現(xiàn)WinForm全屏置頂?shù)氖纠a
我們?cè)谶\(yùn)行一些?Windows?應(yīng)用程序的時(shí)候,需要將其運(yùn)行在窗體置頂?shù)哪J?并且進(jìn)入全屏狀態(tài),本文將介紹如何使用?C#?來(lái)實(shí)現(xiàn)?WinForm?的全屏置頂?shù)幕竟δ?感興趣的可以了解下2024-12-12
C#實(shí)現(xiàn)數(shù)據(jù)去重的方式總結(jié)
這篇文章主要來(lái)和大家一起來(lái)討論一下關(guān)于C#數(shù)據(jù)去重的常見(jiàn)的幾種方式,每種方法都有其特點(diǎn)和適用場(chǎng)景,感興趣的小伙伴可以了解一下2023-07-07
Unity中Instantiate實(shí)例化物體卡頓問(wèn)題的解決
這篇文章主要為大家詳細(xì)介紹了Unity實(shí)現(xiàn)離線計(jì)時(shí)器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-10-10
C#中多維數(shù)組[,]和交錯(cuò)數(shù)組[][]的區(qū)別
這篇文章介紹了C#中多維數(shù)組[,]和交錯(cuò)數(shù)組[][]的區(qū)別,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-01-01

