c#中winform內嵌webbrowser控件基本使用

//WebBrowser控件禁用腳本錯誤
webBrowser1.ScriptErrorsSuppressed = true;

//使JavaScript可調用winform後臺方法
webBrowser1.ObjectForScripting = this;

//JavaScript調用winform後臺方法
var oLiveViews = window.exteral.GetViews();//GetViews()爲後臺方法

//加載網頁
webBrowser1.Url = new Uri(“https://www.csdn.net/);

//網頁加載完畢事件
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);

//根據標籤id獲取表單元素,但網頁中存在iframe標籤會獲取不到元素
HtmlElement webBrowser1.Document.GetElementById("txtUserName");

//獲取網頁中所有iframe
HtmlWindowCollection winCollection = webBrowser1.Document.Window.Frames;

//遍歷所有frame
foreach (HtmlWindow htmlWindow in winCollection)
{
	//根據標籤id獲取iframe中的表單元素
	HtmlElement clsbdmh6ele = htmlWindow.Document.GetElementById("clsbdmh6");
}

//獲取某個元素下的所有子元素
HtmlElementCollection collection = webBrowser1.Document.GetElementById("menu").Children

//遍歷所有HtmlElement
foreach (HtmlElement item in collection)
{
	if (item.FirstChild.InnerText == "車輛檔案")
    {
    	////獲取表單元素的某個屬性
    	string rel = item.FirstChild.GetAttribute("rel");
        string rel1 = item.FirstChild.GetAttribute("rel1");
        string className = item.FirstChild.GetAttribute("cs-navi-tab");
        Object[] args = new string[2] { rel1, rel };
        //調用頁面中的JavaScript
        webBrowser1.Document.InvokeScript("addTab", args);
        }
     }
}

//調用按鈕點擊事件
htmlWindow.Document.GetElementById("save").InvokeMember("Click");

//解決點擊網頁按鈕後,網頁還沒加載完,導致後面代碼獲取不到表單元素問題的簡(無)單(腦)辦法
private void Delay(int Millisecond)
{
	DateTime current = DateTime.Now;
	while (current.AddMilliseconds(Millisecond) > DateTime.Now)
	{
		Application.DoEvents();
	}
	return;
}

//解決自動彈出IE瀏覽器問題
private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
{
	if (AppHelper.hbPlatformMaker == (int)AppHbPlatformMaker.zkyt)
	{
		e.Cancel = true;//取消彈窗
		string hbptUrl = AppHelper.hbPlatfromAddress;
		Log.Instance.Info("AppHelper.hbPlatfromAddress:" + hbptUrl);
		if (hbptUrl.LastIndexOf('/') == hbptUrl.Length - 1)
		{
			//webBrowser加載url
			hbptUrl = hbptUrl.Substring(0, hbptUrl.Length - 1) + "/index.jsp";
			Log.Instance.Info("TargetAddress:" + hbptUrl);
			webBrowser1.Navigate(hbptUrl);
		}
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章