C#的WebBrowser的操作與注意事項介紹

來源:互聯網
上載者:User

1.在Winform裡使用WebBrowser,要對Form1.cs添加一些東西:
1.1 在“public partial class Form1 : Form”上方,添加:

複製代碼 代碼如下:[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]

1.2 在Form1的Shown事件中,添加:

複製代碼 代碼如下:this.UI_webBrowser.ObjectForScripting = this;

2.由於WebBrowser是放在Winform介面中,由介面線程(主線程)管理,執行渲染也是主線程,因此,不能把商務邏輯放在主線程中,應該另開一個線程,執行商務邏輯。並通過Invoke來與WebBrowser互動。

例子:

複製代碼 代碼如下:private void Form1_Shown(object sender, EventArgs e)
{
this._thread_mainLogic = new Thread(this.ThreadFunction_MainLogic);
this._thread_mainLogic.Start();
}

private void ThreadFunction_MainLogic()
{
Debugger.Log(0, "", "\r\n開始執行商務邏輯\r\n");
this.Invoke( new Action( () => { this.webBrowser.Navigate("http://www.baidu.com");} ) );//通過Invoke來與webBrowser互動
.....
}

3.瀏覽指定URL。注意,此方法為非同步方法呼叫,需要手動同步。

複製代碼 代碼如下://以下方法不是安全執行緒方法
private AutoResetEvent _threadControlEvent_Tool_webBrowser_Navigate = null;

private void Tool_webBrowser_Navigate(string arg_URL)
{
this._threadControlEvent_Tool_webBrowser_Navigate = new AutoResetEvent(false);
this.Invoke(new Action(() =>
{
this.webBrowser.DocumentCompleted += webBrowser_DocumentCompleted_Tool_webBrowser_Navigate;
this.webBrowser.Navigate(arg_URL);
}));
this._threadControlEvent_Tool_webBrowser_Navigate.WaitOne();
this._threadControlEvent_Tool_webBrowser_Navigate.Close();
this._threadControlEvent_Tool_webBrowser_Navigate.Dispose();
}

void webBrowser_DocumentCompleted_Tool_webBrowser_Navigate(object sender, WebBrowserDocumentCompletedEventArgs e)
{
this.webBrowser.DocumentCompleted -= webBrowser_DocumentCompleted_Tool_webBrowser_Navigate;
this._threadControlEvent_Tool_webBrowser_Navigate.Set();
}

4.根據ID擷取按鈕,並點擊它:(也可作用於網頁中的URL連結)

複製代碼 代碼如下://假設網頁裡的按鈕,ID為"btn"
HtmlElement element_btn = null;
this.Invoke(new Action(() => { element_btn = this.UI_webBrowser.Document.All["btn"]; }));//擷取
element_btn.InvokeMember("Click");//點擊,此方法為同步方法,可安全使用

5.根據ID擷取輸入框,並輸入內容

複製代碼 代碼如下://假設網頁裡的輸入框,ID為"input"
HtmlElement input = null;
this.Invoke( new Action( () => { input = this.UI_webBrowser.Document.All["input"]; } ) );//擷取
input.InnerText = "123";//輸入"123"。此方法不為同步方法,需要使用下文的Wait_SafeMode方法。
Tool_Wait_SafeMode();//實現在下文

6.根據ID擷取form,並提交(submit)

複製代碼 代碼如下://假設網頁裡的form,ID為"form2"
HtmlElement form2 = null;
this.Invoke( new Action( () => { form2 = this.UI_webBrowser.Document.Forms["form2"]; } ) );//擷取
form_submit.InvokeMember("submit");//提交form2裡的內容。此方法為同步方法,可安全使用。

7.根據ID擷取CheckBox,並設定為已選中(Checked)

複製代碼 代碼如下://假設網頁裡的CheckBox,ID為"checkbox5"
HtmlElement checkBox5 = null;
this.Invoke( new Action( () => { checkBox5 = this.UI_webBrowser.Document.All["checkbox5"]; } ) );//擷取
checkBox5.SetAttribute("Checked", "true");//設定為已選中。此方法為同步方法,可安全使用。

8.根據元素的已知屬性,來尋找該元素

複製代碼 代碼如下://假設網頁裡,有且僅有這樣的一個元素:它有一個名為"value"的屬性,屬性值為"12345"
bool isFind = false;
HtmlElementCollection htmlElementCollection = null;
this.Invoke( new Action( () => { htmlElementCollection = this.webBrowser.Document.All; } ) );//擷取集合
HtmlElement resultElement = null;

foreach (HtmlElement currentElement in htmlElementCollection)//在集合中遍曆所有元素來尋找
{
if (currentElement.GetAttribute("value") == "12345")
{
isFind = true;
resultElement = currentElement;
break;
}
}

if( ! isFind )
{
對沒有找到的情況進行處理;
}

9.對網頁中的ComboBox進行設定。注意,以下代碼有問題,請勿使用。由於SetAttribute是一個沒有回應的API,因此建議使用js來進行設定。下文中,讓WebBrowser執行js代碼,可以做到有回調。

複製代碼 代碼如下://假設網頁中存在一個ComboBox,ID為"comboBox123",下拉式功能表有兩項:
//第一項的ID為1,value為"蘋果"
//第二項的ID為2,value為"西瓜"
HtmlElement element_comboBox = null;
this.Invoke( new Action( () => { element_comboBox = this.webBrowser.Document.All["comboBox123"]; } ) );//擷取
Tool_Wait_SafeMode();
this.Invoke( new Action( () => { element_comboBox.SetAttribute("value", "2"); } ) );//設定為"西瓜",即value = 2
Tool_Wait_SafeMode();

10.Tool_Wait_SafeMode

複製代碼 代碼如下:private void Tool_Wait_SafeMode()
{
bool isError = false;
bool isBusy = false;
do
{
this.Invoke(new Action(() =>
{
try
{
isBusy = this.webBrowser.IsBusy;
}
catch (System.Exception ex)
{
isError = true;
}
}));
if (isError)
{
Thread.Sleep(errorWaitTime);//建議為2秒以上。這個時間要根據機器效能來設定,必須設定長一些。
}
else
{
if (isBusy)
{
Thread.Sleep(arg_waitTime);//建議為0.1秒以上。這個時間要根據機器效能來設定,可以設定短一些。
}
}
}
while (isError | isBusy);
}

11.在網頁中執行js代碼

由於讓WebBrowser執行js,是一個非同步過程,並且還需要回調,因此這個功能有些複雜。對此進行了封裝,把它封裝為了一個同步過程,來方便使用:

複製代碼 代碼如下:#region private void Tool_webBrowser_ExecUserJSScript(string arg_jsCodes)
private AutoResetEvent _threadControlEvent_Tool_webBrowser_ExecUserJSScript_Init = null;
private AutoResetEvent _threadControlEvent_Tool_webBrowser_ExecUserJSScript_Exec = null;
private object _returnObj_Tool_webBrowser_ExecUserJSScript = null;

/// <summary>
/// 用WebBrowser執行JS自訂語句。
/// 1:定義一個js方法,方法名盡量特殊些,以免與html裡已存在的js方法重名。這個方法的結尾,一定要使用window.external.NotifyCSharpComplete( msg );才能實現js執行結束後,通知CSharp。把這個方法傳遞給參數arg_jsFunctionDefineCodes。
/// 2:把這個方法的方法名,傳遞給參數arg_jsFunctionName。
/// 3: 把這個方法,需要傳遞的參數,傳遞給arg_functionArgs。如果不需要傳入參數,該欄位可以不需要賦值,或賦值為null,或賦值為new object[]{}。
/// 4: 如果js在回調C#時,不需要返回參數,請在js方法裡使用window.external.NotifyCSharpComplete( null );如果有返回參數,則可以修改為window.external.NotifyCSharpComplete( 參數變數 );
/// 例子:js方法:function jsFunctionTest( arg1, arg2 ) { var arg3 = arg1 + arg2; window.external.NotifyCSharpComplete( "運算結果:" + arg3 ); }
/// 則 arg_jsFunctionDefineCodes = "function jsFunctionTest( arg1, arg2 ) { var arg3 = arg1 + arg2; window.external.NotifyCSharpComplete( \"運算結果:\" + arg3 ); }";
/// arg_jsFunctionName = jsFunctionTest
/// 如果需要傳遞的參數為123、456,則arg_functionArgs = new object[] { 123, 456 }
/// 傳回值,通過object進行返回。如果object是一個其他類型,則請自行轉換。比如:stirng result = (string)Tool_webBrowser_ExecUserJSScript(...);
/// </summary>
/// <param name="arg_jsFunctionDefineCodes">js方法,注意,總長度不能超過1991(總長不能超過2048,程式中會對字串添加一些內容。)</param>
/// <param name="arg_jsFunctionName">js方法的方法名</param>
/// <param name="arg_functionArgs">js方法的參數列表。如果不需要傳入參數,該欄位可以不需要賦值,或賦值為null,或賦值為new object[]{}</param>
/// <returns>返回執行結果。注意,預設為返回參數。如果沒有返回,請修改js方法,把NotifyCSharpComplete( msg )改為NotifyCSharpComplete( null )</returns>
private object Tool_webBrowser_ExecUserJSScript(string arg_jsFunctionDefineCodes, string arg_jsFunctionName, object[] arg_functionArgs = null)
{
this._returnObj_Tool_webBrowser_ExecUserJSScript = null;
if (arg_jsFunctionDefineCodes.Length > 1991)
{
throw new Exception("錯誤:js方法定義的長度超過了1991。");
}
//1.寫入js方法。
arg_jsFunctionDefineCodes = "javascript:" + arg_jsFunctionDefineCodes + ";window.external.NotifyCSharpCompleteInit();";
if (arg_jsFunctionDefineCodes.Length >= 2048)
{
throw new Exception("錯誤:js方法定義的總長度超過了2048(原始方法 + 添加的內容)。");
}
this._threadControlEvent_Tool_webBrowser_ExecUserJSScript_Init = new AutoResetEvent(false);
this.Invoke(new Action(() =>
{
this.webBrowser.Navigate(arg_jsFunctionDefineCodes);
}));
this._threadControlEvent_Tool_webBrowser_ExecUserJSScript_Init.WaitOne();
this._threadControlEvent_Tool_webBrowser_ExecUserJSScript_Init.Close();
this._threadControlEvent_Tool_webBrowser_ExecUserJSScript_Init.Dispose();
//2.執行js方法
this._threadControlEvent_Tool_webBrowser_ExecUserJSScript_Exec = new AutoResetEvent(false);
this.Invoke(new Action(() =>
{
this.webBrowser.Document.InvokeScript(arg_jsFunctionName, arg_functionArgs);
}));
this._threadControlEvent_Tool_webBrowser_ExecUserJSScript_Exec.WaitOne();
this._threadControlEvent_Tool_webBrowser_ExecUserJSScript_Exec.Close();
this._threadControlEvent_Tool_webBrowser_ExecUserJSScript_Exec.Dispose();
//3.返回參數
return this._returnObj_Tool_webBrowser_ExecUserJSScript;
}

public void NotifyCSharpCompleteInit()
{
this._threadControlEvent_Tool_webBrowser_ExecUserJSScript_Init.Set();
}

public void NotifyCSharpComplete(object arg_obj)
{
this._returnObj_Tool_webBrowser_ExecUserJSScript = arg_obj;
this._threadControlEvent_Tool_webBrowser_ExecUserJSScript_Exec.Set();
}
#endregion

用法例子1:

複製代碼 代碼如下:string jsCmdTest = "function testFunction( msg ) { setTimeout(\"window.external.NotifyCSharpComplete(\\\"返回內容\\\");\", 5000);};";
object returnObj = this.Tool_webBrowser_ExecUserJSScript(jsCmdTest, "testFunction", new object[] {"傳入參數"});
string returnStr = returnObj as string;

用法例子2:

複製代碼 代碼如下:string jsCmdTest = "function testFunction( ) { var a = 122; var b = 244; var c = a + b; window.external.NotifyCSharpComplete(c);};";
object returnObj = this.Tool_webBrowser_ExecUserJSScript(jsCmdTest, "testFunction", null);
int returnInt = (int)returnObj;

用法例子3:

複製代碼 代碼如下:string jsCmdTest = "function testFunction( ) { window.external.NotifyCSharpComplete(null);};";
object returnObj = this.Tool_webBrowser_ExecUserJSScript(jsCmdTest, "testFunction", null);
string result = "js執行完畢";

總結:使用WebBrowser的兩個大問題:

1.WebBrowser是調用機器上的IE,因此版本、渲染的程式也就取決與IE的版本與渲染器的程式。

2.WebBrowser的執行js等很多操作都是非同步且無事件回應的,只能自己去估算一個執行時間,來等待。並且等待時間一定要大於js實際執行時間,否則後續代碼會出問題。

3.目前,執行js的方式,只能通過瀏覽器的地址欄。地址欄是有長度限制的。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.