Webbrowser has some experience. If two-way communication is implemented between JavaScript and winform code

Source: Internet
Author: User

Recently, I learned how to embed the webbrowser control in winform and interact with JavaScript on the HTM page.

In general, JavaScript and winform Code call each other, and JavaScript and server in Web DevelopmentCodeThere are similarities between mutual calls through Ajax.

Three examples are provided below:

 

1. Place the webbrowsercontrol in winform. then, write a page1.htm file with the following content:








button

I will show this page1.htm in webbrowser. It is not hard to write. Just add the upper and lower sentences in winform.
Webbrowser1.url = new uri ("C: \ workspace \ windowsformsapp \ page1.htm ");

Then run. The HTM is displayed in webbrowser of winform. click the button to call the JavaScript function and the alert prompt is displayed. Everything is normal and there is nothing unusual.

 

2. if I move the functions in JavaScript to the CS code of winform, can the HTM page still be called?
This is a bit of Ajax, and how to call webpage in the client's JavaScript. aspx. the code in CS, at that time in ajaxpro, needs to be in webpage. aspx. register this page in the CS code for Ajax use, and declare it before the function.

To call the code in winform, set comvisibleattribute (true) for winform and set the webbrowser1.objectforscripting attribute for the webbrowser control.
Webbrowser1.url = new uri ("C: \ workspace \ windowsformsapp \ page1.htm ");
Webbrowser1.objectforscripting = this;

In fact, if you do well, you can classify the code into a class to facilitate management. Here it becomes: webbrowser1.objectforscripting = new class;

 

Then, write a function in winform.
Public void test (string message)
{
MessageBox. Show (message, "client code ");
}

Finally, the test method name must be prefixed with window. External in htm.
<Button onclick = "window. External. Test ('test called from Windows Code')"> button </button>

 

Then run it again and you will find that the onclick event in HTM can actually call the code in winform, which is amazing!

 

The complete winform code is as follows:
Using system;
Using system. Windows. forms;
Using system. Security. permissions;

Namespace windowsformsapp
{
[Permissionset (securityaction. Demand, name = "fulltrust")]
[System. runtime. interopservices. comvisibleattribute (true)]
Public partial class form2: Form
{
Private webbrowser webbrowser1 = new webbrowser ();

Public form2 ()
{
Initializecomponent ();

Button1.text = "call script code from client code ";
Button1.dock = dockstyle. Top;
Button1.click + = new eventhandler (button#click );
Webbrowser1.dock = dockstyle. Fill;
Controls. Add (webbrowser1 );
Load + = new eventhandler (form2_load );

}

private void form2_load (Object sender, eventargs e)
{< br> webbrowser1.allowwebbrowserdrop = false;
Accept = false;
webbrowser1.webbrowsershortcutsenabled = false;
webbrowser1.objectforscripting = This;
webbrowser1.url = new uri ("C: \ workspace \ windowsformsapp \ page1.htm ");
}

Public void test (string message)
{
MessageBox. Show (message, "client code ");
}
}
}

To sum up, the key webbrowser1.objectforscripting attributes, comvisibleattribute (true), and window. External.

Msdn says the function of the webbrowser1.objectforscripting attribute is to get or set an object that can be accessed by the script code contained in the web page displayed in the webbrowser control. This attribute enables web pages hosted by the webbrowser control and applications containing the webbrowser control.ProgramCommunication. This attribute can be used to integrate dynamic HTML (DHTML) code with client application code. The object specified for this attribute can be used as a window. External Object (built-in DOM object for host access) for webpage scripts.

 

You can set this attribute to any com-visible object that you want its public attributes and methods to be used for script code. You can use comvisibleattribute to mark a class as a class visible to com.
This step is also crucial. If comvisibleattribute (true) is not set, the program cannot load the display HTM page, because the HTM uses window. external. test () method. If the class of the method does not comvisible, it cannot be accessed. Conversely, if comvisible is set but the webbrowser1.objectforscripting attribute is not set, an error is reported during code execution: window. External is invalid or the object cannot be found.

 

The lack of window. External makes it even more difficult. Therefore, these three are indispensable.

 

Let's look at this window. External, which is not found in common JavaScript books, but is very useful. A common application is:
<Input type = "button" name = "button" value = "add" onclick = "window. External. AddFavorite (location. href, document. Title)"/>

 

Reference other people's "in the project embedded in the browser, in addition to the external methods provided by IE by default, you need to be able to call C ++ code in the webpage script. To achieve this interaction, script extension is required. The implementation of script extension is to implement an idispatch interface in the program. The interface pointer is returned through the ongetexternal virtual function of the chtmlview class, so that the window can be used in the script. external. XXX (the keyword window can be omitted) to reference the method or attribute exposed by the interface (XXX is the method or attribute name ). "

 

Let's look at the script extension in C #. You only need webbrowser1.objectforscripting and comvisibleattribute (true) to complete the simple setting! Happy! Sad reminder!

3. Let's look at another one. Can I call JavaScript on the HTML page from winform code?
Page1.htm: Delete the button and only keep the Javascript script.
<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en">
<HTML>
<Head>
<Title> </title>
<SCRIPT type = "text/JavaScript">
Function Test (Message)
{
Alert (Message );
}
</SCRIPT>
</Head>
<Body>

</Body>
</Html>

Using system;
Using system. Windows. forms;
Using system. Security. permissions;

Namespace windowsformsapp
{
[Permissionset (securityaction. Demand, name = "fulltrust")]
[System. runtime. interopservices. comvisibleattribute (true)]
Public partial class form2: Form
{
Private webbrowser webbrowser1 = new webbrowser ();
Private button button1 = new button ();

Public form2 ()
{
Initializecomponent ();

Button1.text = "call script code from client code ";
Button1.dock = dockstyle. Top;
Button1.click + = new eventhandler (button#click );
Webbrowser1.dock = dockstyle. Fill;
Controls. Add (webbrowser1 );
Controls. Add (button1 );
Load + = new eventhandler (form2_load );

}

private void form2_load (Object sender, eventargs e)
{< br> webbrowser1.allowwebbrowserdrop = false;
Accept = false;
webbrowser1.webbrowsershortcutsenabled = false;
webbrowser1.objectforscripting = This;
webbrowser1.url = new uri ("C: \ workspace \ windowsformsapp \ page1.htm ");
}

Private void button#click (Object sender, eventargs E)
{
Webbrowser1.document. invokescript ("test ",
New String [] {"called from client code "});
}

}
}

This time the key factor is webbrowser1.document. invokescript, while webbrowser1.objectforscripting and comvisible are no longer needed.

The htmldocument. invokescript method is used to execute dynamic script functions defined on the HTML page.

So far, JavaScript and winform code can be called each other, and it feels similar to web development.

 

This technique is called bidirectional communication between JavaScript (DHTML) Code and client application code.

Related Article

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.