C # WebBrowser Operations and considerations Introduction _c# Tutorials

Source: Internet
Author: User

1. To use WebBrowser in WinForm, add something to Form1.cs:
1.1 on the "public partial class Form1:form", add:

Copy Code code as follows:

[PermissionSet (SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute (True)]

1.2 In the Form1 shown event, add:

Copy Code code as follows:

This. Ui_webbrowser.objectforscripting = this;

2. Because WebBrowser is placed in the WinForm interface, managed by the interface thread (main thread), performing rendering is also the main thread, therefore, the business logic should not be placed in the main thread, and the business logic should be opened separately. and interacts with WebBrowser by Invoke.

Example:

Copy Code code as follows:

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 start execution business logic \ r \ n");
This. Invoke (New Action () => {this.webBrowser.Navigate ("http://www.baidu.com");}); /through invoke to interact with WebBrowser
.....
}

3. Browse to the specified URL. Note that this method is an asynchronous method and requires manual synchronization.

Copy Code code as follows:

The following method is not a thread-safe method
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. According to the ID get button, and click it: (also can be used for Web page URL link)

Copy Code code as follows:

Suppose the button in the page, id "BTN"
HtmlElement element_btn = null;
This. Invoke (New Action () => {element_btn = this. ui_webbrowser.document.all["BTN"]; });//Get
Element_btn. InvokeMember ("click");//Click, this method is synchronous method, safe to use

5. Get the input box according to the ID and enter the content

Copy Code code as follows:

Suppose the input box in the page, ID is "input"
HtmlElement input = null;
This. Invoke (New Action () => {input = this. ui_webbrowser.document.all["Input"]; });//Get
Input. innertext = "123";//Enter "123". This method is not a synchronization method and requires the use of the Wait_safemode method below.
Tool_wait_safemode ()//implemented in the following

6. Obtain form according to ID and submit (Submit)

Copy Code code as follows:

Suppose the form,id in the Web page is "Form2."
HtmlElement Form2 = null;
This. Invoke (New Action () => {Form2 = this. ui_webbrowser.document.forms["Form2"]; });//Get
Form_submit. InvokeMember ("submit");//Submit the contents of Form2. This method is a synchronous method and can be used safely.

7. Get checkbox based on ID and set to checked (Checked)

Copy Code code as follows:

Suppose the checkbox,id in the Web page is "checkbox5."
HtmlElement checkBox5 = null;
This. Invoke (New Action () => {checkBox5 = this. ui_webbrowser.document.all["CHECKBOX5"]; });//Get
Checkbox5.setattribute ("Checked", "true");//set to selected. This method is a synchronous method and can be used safely.


8. Find the element based on the known properties of the element

Copy Code code as follows:

Let's say that there is one element in the Web page that has an attribute named "Value" with a property value of "12345".
BOOL Isfind = false;
HtmlElementCollection htmlelementcollection = null;
This. Invoke (New Action (() => {htmlelementcollection = this.webBrowser.Document.All;})); /Get Collection
HtmlElement resultelement = null;

foreach (HtmlElement currentelement in htmlelementcollection)//iterates through all elements in the collection to find
{
if (Currentelement.getattribute ("value") = = "12345")
{
Isfind = true;
Resultelement = currentelement;
Break
}
}

if (! Isfind)
{
To deal with a situation which is not found;
}


9. Set the ComboBox in the Web page. Note that there is a problem with the following code, please do not use. Because SetAttribute is an API that does not respond, it is recommended that you use JS to set it up. Below, let WebBrowser execute JS code, can do have callback.

Copy Code code as follows:

Suppose there is a Combobox,id "comboBox123" in the Web page, and there are two items in the Drop-down menu:
ID of the first item is 1,value as "apple"
The second item ID is 2,value as "watermelon"
HtmlElement element_combobox = null;
This. Invoke (New Action (() => {element_combobox = this.webbrowser.document.all["comboBox123"];}); /Get
Tool_wait_safemode ();
This. Invoke (New Action () => {element_combobox.setattribute ("value", "2");}); /set to "watermelon", that is, value = 2
Tool_wait_safemode ();

10.tool_wait_safemode

Copy Code code as follows:

private void Tool_wait_safemode ()
{
BOOL IsError = false;
BOOL IsBusy = false;
Todo
{
This. Invoke (New Action () =>
{
Try
{
IsBusy = This.webBrowser.IsBusy;
}
catch (System.Exception ex)
{
IsError = true;
}
}));
if (isError)
{
Thread.Sleep (Errorwaittime)//recommended for more than 2 seconds. This time is set according to machine performance and must be set to a little longer.
}
Else
{
if (isbusy)
{
Thread.Sleep (Arg_waittime)//recommended for more than 0.1 seconds. This time to be set according to machine performance, you can set a short number.
}
}
}
while (IsError | isbusy);
}

11. Execute the JS code in the Web page

This functionality is somewhat complicated by having WebBrowser execute JS, an asynchronous process that requires a callback. This is encapsulated and encapsulated for a synchronous process to facilitate the use of:

Copy Code code as follows:

#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>
Execute JS Custom statements with WebBrowser.
1: The definition of a JS method, the method name as much as possible, so as to avoid the existing in HTML with the JS method duplicate. At the end of this method, be sure to use Window.external.NotifyCSharpComplete (msg) to implement JS execution after the notification CSharp. Pass this method to the parameter arg_jsfunctiondefinecodes.
2: Pass the method name of this method to the parameter arg_jsfunctionname.
3: Put this method, need to pass the parameter, pass to Arg_functionargs. If you do not need to pass in the argument, the field can not be assigned a value, or the assignment is null, or the assignment is new object[]{}.
4: If JS in the callback C #, do not need to return parameters, please use Window.external.NotifyCSharpComplete (null) in the JS method, if there are return parameters, It can be modified to Window.external.NotifyCSharpComplete (parameter variable);
Example: Js method: Function Jsfunctiontest (arg1, arg2) {var arg3 = arg1 + arg2; Window.external.NotifyCSharpComplete ("Operation Result:" + Arg3); }
Then Arg_jsfunctiondefinecodes = "function Jsfunctiontest (arg1, arg2) {var arg3 = arg1 + arg2; Window.external.NotifyCSharpComplete (\ "Operation result: \" + arg3); }";
Arg_jsfunctionname = Jsfunctiontest
If the parameter to pass is 123, 456, then Arg_functionargs = new object[] {123, 456}
Returns a value that is returned by object. If object is a different type, convert it yourself. For example: stirng result = (string) tool_webbrowser_execuserjsscript (...);
</summary>
<param name= the "Arg_jsfunctiondefinecodes" >js method, note that the total length can not exceed 1991 (the total can not exceed 2048, the program will add some content to the string.) ) </param>
<param Name= The method name of the "Arg_jsfunctionname" >js method </param>
<param name= The parameter list of the "Arg_functionargs" >js method. If you do not need to pass in the argument, the field may not need to be assigned a value, or the assignment is null, or the value is assigned to the new object[]{}</param>
<returns> returns execution results. Note that the default is the return parameter. If not, please modify the JS method to change Notifycsharpcomplete (msg) to 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 (Error: JS method definition has a length of more than 1991. ");
}
1. Write JS method.
Arg_jsfunctiondefinecodes = "javascript: + Arg_jsfunctiondefinecodes +"; Window.external.NotifyCSharpCompleteInit () ;";
if (arg_jsfunctiondefinecodes.length >= 2048)
{
throw new Exception (Error: The total length of the JS method definition exceeds 2048 (the original method + added content). ");
}
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. Execute JS method
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 parameters
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

Usage Example 1:

Copy Code code as follows:

String jscmdtest = "function TestFunction (msg) {settimeout (\" Window.external.NotifyCSharpComplete (\\\ "return content \\\"); \ ", 5000);}; ";
Object returnobj = this. Tool_webbrowser_execuserjsscript (Jscmdtest, "TestFunction", new object[] {"Incoming parameters"});
String returnstr = Returnobj As String;

Usage Example 2:

Copy Code code as follows:

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;

Usage Example 3:

Copy Code code as follows:

String jscmdtest = "function TestFunction () {window.external.NotifyCSharpComplete (null);};";
Object returnobj = this. Tool_webbrowser_execuserjsscript (Jscmdtest, "testfunction", null);
string result = "JS execution completed";

Summary: Two big questions about using WebBrowser:

1.WebBrowser is called IE on the machine, so the version, rendering program also depends on the version of IE and the renderer program.

2.WebBrowser of the implementation of JS and many other operations are asynchronous and no event response, can only estimate an execution time, to wait. And wait time must be greater than JS actual execution time, otherwise the subsequent code will be problematic.

3. At present, the implementation of JS way, only through the browser's address bar. The Address bar has a length limit.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.