做WEB开发的想把网页做成应用程序的界面,开发应用程序的又想把程序界面做得和WEB一样。本文介绍一下用HTML做软件UI用到的的一些技术。

其实HTML UI也不是什么新鲜事了,Norton Antivirus从几年前的版本就开始用了,vs.net2002中的开始页也用了这个技术。


[方案一,适用于vs2002~2005(vb/delphi等类似)]

1、导入web browser COM控件

 2、实现IDocHostUIHandler接口,MSDN中有介绍WebBrowser Customization 。

 IDocHostUIHandler接口有十几个方法,这里我们只关心这个:void IDocHostUIHandler.GetExternal(out object ppDispatch)

当在浏览器脚本中调用 window.external时就会调用这个方法,我们需要在返回一个对象。

如:

…
public class Form1 : Form, IDocHostUIHandler
…
        public Form1()
        { 
 
            InitializeComponent();
            object flags=0;
            object targetFrame=String.Empty;
            object postData=String.Empty;
            object headers=String.Empty;
            this.WebBrowser.Navigate( "about:blank", ref flags, ref targetFrame, ref postData, ref headers );
            ICustomDoc cDoc=(ICustomDoc)this.WebBrowser.Document;
            cDoc.SetUIHandler( (IDocHostUIHandler)this );
            this.WebBrowser.Navigate(@".",ref flags, ref targetFrame, ref postData, ref headers );
        }
              void IDocHostUIHandler.GetExternal(out object ppDispatch)
              { 
 
                     ppDispatch = new Hello ();
              }
…

添加Hello类的代码,注意:此类一定要加上ComVisible=true特性,或是给整个程序集加上[assembly: ComVisible( true )]。

[ComVisible(true)]
    public class Hello
       { 
 
              public void Haha(string msg)
              { 
 
           MessageBox.Show( msg );
               
              }
       }

这样,就可以在浏览器中用脚本这样调用 

<script language="JavaScript" id="clientEventHandlersJS">
       <!--
       function callHostUI(msg)
        { 
 
               window.external. Haha (msg);
        }callHostUI(“hello wuChang”);
       -->
       </script>

 [方案二,适用于vs2005]

 VS2005提供的WebBrowser控件,已经实现了IDocHostUIHandler接口,使用起来就更简单了。

WebBrowser提供了public Object ObjectForScripting { get; set; }

属性,只需要这样用就行了。

webBrowser1.ObjectForScripting = new Hello ();

调用浏览器用的脚本可以这样

webBrowser1.Document.InvokeScript("js函数名",

            new String[] { "参数列表 " });

更多的内容在.net FW SDK (ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.NETDEVFX.v20.chs/CPref17/html/P_System_Windows_Forms_WebBrowser_ObjectForScripting.htm)里有介绍。

 .net2.0在System.Windows.Forms name spaces中提供HtmlDocument、HtmlElement等访问HTML元素的控件,使用方法在SDK里有,这里就不介绍了。