This method is suitable for embedding WebBrowser in C # to interact with the C # background code on pages loaded in the browser.
I. C # Program
1. Add WebBrowser to the C # form and add the URL of the page to the browser.
2. Add using System. Runtime. InteropServices to the form code; // interact with Html pages.
Add [ComVisible (true)] in the previous line of the class // interact with the Html page
Add
This. webB. ObjectForScripting = this; // interacts with Html pages.
For example:
Using System. Runtime. InteropServices;
Namespace slgdjb {[ComVisible (true)]Public partial class Frm_Index: Form {public Frm_Index () {InitializeComponent ();This. webB. ObjectForScripting = this;}
}
}
3. Add a method for calling Html pages
For example:
The method name is the name of the method to be called in Html page JS.
Public stringMyAction(Object para) {// Method Content written here}
4. the C # program calls the Html page JS method.
First, obtain the Document of the Html page, and then call the JS method of the Html page.
For example:
HtmlDocument doc = webB. Document; string [] objArray = new string [2]; objArray [0] = "";
ObjArray [1] = "B ";// Call the js method of the Html page. JSMonth is the JS method name, And objArray is the passed parameter.
// JS cannot receive objects, but can receive integer, string, and string arrays. Doc. InvokeScript ("JSMonth", objArray );
Ii. JS method Calling C # method on the Html page
1. Call the method of the C # program in JavaScript on the Html page. If the method in C # has a return value, JS can get it.
For example:
//MyActionIt is the method name of the method in C #, and para is the parameter of this method.
Var str = window. external.MyAction(Para );
2. JS methods in Html pages for C # Calls
The method name in this method is called in C #. The method name obj is the parameter to be passed. If the input parameter is an array
You can directly use arguments [index (array parameter number)] to represent the parameter value of the array. Arguments is the default array parameter of JS. The advantage is that the JS method does not have to write the passed parameter.
FunctionJSMonth(Obj ){
// If obj is an array, obj [0] is equivalent to arguments [0]. Its method name can be changed to JSMonth ()
}