欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#通过html调用WinForm的方法

程序员文章站 2023-09-08 10:12:52
本文实例讲述了c#通过html调用winform的方法。分享给大家供大家参考,具体如下: 完整测试代码: form1.cs: using system; u...

本文实例讲述了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();
    }
  }

网页:

<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
  <head>
    <title></title>
    <script language="javascript" type="text/javascript">
      function messagebox(message)
      {
        alert(message);
      }
    </script>
  </head>
  <body>
    <button onclick="window.external.mymessagebox('javascript访问c#代码')">javascript访问c#代码</button>
      <a href="javascript:window.external.mymessagebox1()">javascript访问c#代码</a>
    <a href="javascript:window.external.showform()">javascript访问c#代码</a>
  </body>
</html>

补充:

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#相关内容感兴趣的读者可查看本站专题:《winform控件用法总结》、《c#数据结构与算法教程》、《c#常见控件用法教程》、《c#面向对象程序设计入门教程》及《c#程序设计之线程使用技巧总结

希望本文所述对大家c#程序设计有所帮助。