How to call the webbrowser control script in winform

Source: Internet
Author: User
This is a problem on the csdn forum. It may be helpful to other people, so I posted it.

JScript is built on com, and setting variables/calling functions is implemented through idispatch. In. net, the method in idispatch is called through reflection, that is, through system. type. invokemember. This method calls idispatch: getidsofnames and idispatch: invoke to call methods and attributes in the COM automation object. Reference

Binding for office automation servers with Visual C #. net

Suppose there are the following HTML,

<Script language = "JavaScript">
VaR var1 = 'yes ';
Function testx (OBJ)
{
Alert (OBJ );
Alert (var1 );
}
</SCRIPT>
<Input type = button value = "Click me" onclick = "testx ('hello');">

In C #, assume that axwebbrowser1 is your webbrowser control object. If you have loaded the preceding HTML, you can do this,

Mshtml. ihtmldocument2 Doc = (mshtml. ihtmldocument2) axwebbrowser1.document;
Mshtml. ihtmlwindow2 win = (mshtml. ihtmlwindow2) Doc. parentwindow;

// Read the variable value
Object o = win. GetType (). invokemember ("var1", bindingflags. getproperty, null, win, new object [] {});

// Write the variable value
Win. GetType (). invokemember ("var1", bindingflags. setproperty, null, win, new object [] {"New Value "});

// Call Method
Win. GetType (). invokemember ("testx", bindingflags. invokemethod, null, win, new object [] {1 });

It's troublesome, right? Fortunately, we don't need to worry so much, because ihtmlwindow2 has a ready-made method called execScript. We can do this:

Win.exe cscript ("var1 = 'abc';", "JavaScript ");
Win.exe cscript ("testx (12)", "JavaScript ");

Address: http://blog.joycode.com/saucer/archive/2004/10/16/35628.aspx

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.