本文实例讲述了c#通过html调用winform的方法。分享给大家供大家参考,具体如下:
完整测试代码:
form1.cs:
using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.text;
using system.windows.forms;
namespace test
{
[system.runtime.interopservices.comvisibleattribute(true)]
public partial class form1 : form
{
public form1()
{
initializecomponent();
}
private void form1_load(object sender, eventargs e)
{
system.io.fileinfo file = new system.io.fileinfo(application.startuppath+@"\test1.htm");
webbrowser1.url = new uri(file.fullname);
webbrowser1.objectforscripting = this;
}
private void button1_click(object sender, eventargs e)
{
object[] objects = new object[1];
objects[0]="c#访问javascript脚本";
webbrowser1.document.invokescript("messagebox", objects);
}
public void mymessagebox(string message)
{
messagebox.show(message);
}
}
}
类winoper:
[system.runtime.interopservices.comvisibleattribute(true)]
public class winoperationclass
{
public void mymessagebox1()
{
messagebox.show(message);
}
public void showform()
{
form2 f2 = new form2();
f2.windowstate = formwindowstate.normal;
f2.show();
}
}
网页:
function messagebox(message)
{
alert(message);
}
javascript访问c#代码
javascript访问c#代码
javascript访问c#代码
补充:
webbrowser1.objectforscripting = this;
这句话的意思是webbrowser1的脚本执行的com绑定的方法是 从form1 来的,而mymessagebox1和showform却是在winoperationclass类里面的,肯定是不行的。
第一个可以是因为form1里面有mymessagebox这个方法,你吧mymessagebox1和showform移动到form1中或者把mymessagebox移动到winoperationclass里面,再把
webbrowser1.objectforscripting = this;
这句改成
winoperationclass w=new winoperationclass();
webbrowser1.objectforscripting = w;
就可以了
推荐第二种……把所有的 com可见的方法放在一个类里面好维护
希望本文所述对大家c#程序设计有所帮助。