WinFormプロジェクト開発におけるWebBrowser使用例の概要
9065 ワード
この例では、WinFormプロジェクト開発におけるWebBrowserの使い方をまとめています.
1.
2.バックグラウンドでJavascriptスクリプトを呼び出す
3.JavaScriptスクリプト呼び出しバックグラウンドメソッド
スクリプトコード
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 = 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;
}