在 DHTML 代码和客户端应用程序代码之间实现双向通信

可使用 WebBrowser 控件将现有的动态 HTML (DHTML) Web 应用程序代码添加到 Windows 窗体客户端应用程序。You can use the WebBrowser control to add existing dynamic HTML (DHTML) Web application code to your Windows Forms client applications. 如果已投入大量的开发时间用于创建基于 DHTML 的控件,并且想要利用 Windows 窗体丰富的用户界面功能,而无需重写现有代码,这将非常有用。This is useful when you have invested significant development time in creating DHTML-based controls and you want to take advantage of the rich user interface capabilities of Windows Forms without having to rewrite existing code.

WebBrowser 控件使你通过 ObjectForScriptingDocument 属性可以实现客户端应用程序代码和 Web 页的脚本代码间的双向通信。The WebBrowser control lets you implement two-way communication between your client application code and your Web page scripting code through the ObjectForScripting and Document properties. 此外,还可以配置 WebBrowser 控件,以便 Web 控件与应用程序窗体上的其他控件的无缝混合,从而隐藏其 DHTML 实现。Additionally, you can configure the WebBrowser control so that your Web controls blend seamlessly with other controls on your application form, hiding their DHTML implementation. 若要无缝地混合控件,需格式化显示的页面,使其背景色和视觉样式可匹配窗体中的其余部分,并使用 AllowWebBrowserDropIsWebBrowserContextMenuEnabledWebBrowserShortcutsEnabled 属性禁用标准的浏览器功能。To seamlessly blend the controls, format the page displayed so that its background color and visual style match the rest of the form, and use the AllowWebBrowserDrop, IsWebBrowserContextMenuEnabled, and WebBrowserShortcutsEnabled properties to disable standard browser features.

若要在 Windows 窗体应用程序中嵌入 DHTMLTo embed DHTML in your Windows Forms application

  1. 需将 WebBrowser 控件的 AllowWebBrowserDrop 属性设置为 false,以防止 WebBrowser 控件打开放到其上的文件。Set the WebBrowser control's AllowWebBrowserDrop property to false to prevent the WebBrowser control from opening files dropped onto it.

    C#复制

    webBrowser1.AllowWebBrowserDrop = false;
    
    webBrowser1.AllowWebBrowserDrop = False
    
  2. 将控件的 IsWebBrowserContextMenuEnabled 属性设置为 false,以防止 WebBrowser 控件在用户进行右键单击时,显示其快捷方式菜单。Set the control's IsWebBrowserContextMenuEnabled property to false to prevent the WebBrowser control from displaying its shortcut menu when the user right-clicks it.

    C#复制

    webBrowser1.IsWebBrowserContextMenuEnabled = false;
    
    webBrowser1.IsWebBrowserContextMenuEnabled = False
    
  3. 将控件的 WebBrowserShortcutsEnabled 属性设置为 false,以防止 WebBrowser 控件响应快捷键。Set the control's WebBrowserShortcutsEnabled property to false to prevent the WebBrowser control from responding to shortcut keys.

    C#复制

    webBrowser1.WebBrowserShortcutsEnabled = false;
    
    webBrowser1.WebBrowserShortcutsEnabled = False
    
  4. 在窗体的构造函数或 Load 事件处理程序中设置 ObjectForScripting 属性。Set the ObjectForScripting property in the form's constructor or a Load event handler.

    以下代码将窗体类自身用于脚本对象。The following code uses the form class itself for the scripting object.

    备注

    扫描二维码关注公众号,回复: 4159712 查看本文章

    组件对象模型 (COM) 必须能够访问脚本对象。Component Object Model (COM) must be able to access the scripting object. 若要使窗体对 COM 可见,则将 ComVisibleAttribute 属性添加到窗体类中。To make your form visible to COM, add the ComVisibleAttribute attribute to your form class.

    C#复制

    webBrowser1.ObjectForScripting = this;
    
    webBrowser1.ObjectForScripting = Me
    
  5. 实现脚本代码将使用的应用程序代码中的公共属性或方法。Implement public properties or methods in your application code that your script code will use.

    例如,如果对脚本对象使用窗体类,则将以下代码添加到窗体类中。For example, if you use the form class for the scripting object, add the following code to your form class.

    C#复制

    public void Test(String message)
    {
        MessageBox.Show(message, "client code");
    }
    
    Public Sub Test(ByVal message As String)
        MessageBox.Show(message, "client code")
    End Sub
    
  6. 在脚本代码中使用 window.external 对象来访问指定对象的公共属性和方法。Use the window.external object in your scripting code to access public properties and methods of the specified object.

    以下 HTML 代码演示如何通过单击按钮对脚本对象调用方法。The following HTML code demonstrates how to call a method on the scripting object from a button click. 将此代码复制到 HTML 文档的 BODY 元素中,该文档为使用控件的 Navigate 方法所加载的文档,或将其分配到控件的 DocumentText 属性的文档。Copy this code into the BODY element of an HTML document that you load using the control's Navigate method or that you assign to the control's DocumentText property.

    复制

    <button onclick="window.external.Test('called from script code')">  
        call client code from script code  
    </button>  
    
  7. 实现应用程序代码将使用的脚本代码中的函数。Implement functions in your script code that your application code will use.

    以下 HTML SCRIPT 元素提供了示例函数。The following HTML SCRIPT element provides an example function. 将此代码复制到 HTML 文档的 HEAD 元素中,该文档为使用控件的 Navigate 方法所加载的文档,或将其分配到控件的 DocumentText 属性的文档。Copy this code into the HEAD element of an HTML document that you load using the control's Navigate method or that you assign to the control's DocumentText property.

    复制

    <script>  
    function test(message) {   
        alert(message);   
    }  
    </script>  
    
  8. 使用 Document 属性访问客户端应用程序代码中的脚本代码。Use the Document property to access the script code from your client application code.

    例如,将以下代码添加到按钮 Click 事件处理程序中。For example, add the following code to a button Click event handler.

    C#复制

    webBrowser1.Document.InvokeScript("test",
        new String[] { "called from client code" });
    
    webBrowser1.Document.InvokeScript("test", _
        New String() {"called from client code"})
    
  9. 完成 DHTML 调试后,将控件的 ScriptErrorsSuppressed 属性设置为 true,以防止 WebBrowser 控件显示脚本代码问题的错误消息。When you are finished debugging your DHTML, set the control's ScriptErrorsSuppressed property to true to prevent the WebBrowser control from displaying error messages for script code problems.

    C#复制

    // Uncomment the following line when you are finished debugging.
    //webBrowser1.ScriptErrorsSuppressed = true;
    
    ' Uncomment the following line when you are finished debugging.
    'webBrowser1.ScriptErrorsSuppressed = True
    

示例Example

以下完整的代码示例将提供演示应用程序,以方便用于理解此功能。The following complete code example provides a demonstration application that you can use to understand this feature. HTML 代码将通过 DocumentText 属性加载到 WebBrowser 控件中,而不是从单独的 HTML 文件进行加载。The HTML code is loaded into the WebBrowser control through the DocumentText property instead of being loaded from a separate HTML file.

C#复制

using System;
using System.Windows.Forms;
using System.Security.Permissions;

[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public class Form1 : Form
{
    private WebBrowser webBrowser1 = new WebBrowser();
    private Button button1 = new Button();

    [STAThread]
    public static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new Form1());
    }

    public Form1()
    {
        button1.Text = "call script code from client code";
        button1.Dock = DockStyle.Top;
        button1.Click += new EventHandler(button1_Click);
        webBrowser1.Dock = DockStyle.Fill;
        Controls.Add(webBrowser1);
        Controls.Add(button1);
        Load += new EventHandler(Form1_Load);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        webBrowser1.AllowWebBrowserDrop = false;
        webBrowser1.IsWebBrowserContextMenuEnabled = false;
        webBrowser1.WebBrowserShortcutsEnabled = false;
        webBrowser1.ObjectForScripting = this;
        // Uncomment the following line when you are finished debugging.
        //webBrowser1.ScriptErrorsSuppressed = true;

        webBrowser1.DocumentText =
            "<html><head><script>" +
            "function test(message) { alert(message); }" +
            "</script></head><body><button " +
            "onclick=\"window.external.Test('called from script code')\">" +
            "call client code from script code</button>" +
            "</body></html>";
    }

    public void Test(String message)
    {
        MessageBox.Show(message, "client code");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        webBrowser1.Document.InvokeScript("test",
            new String[] { "called from client code" });
    }

}
Imports System
Imports System.Windows.Forms
Imports System.Security.Permissions

<PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
<System.Runtime.InteropServices.ComVisibleAttribute(True)> _
Public Class Form1
    Inherits Form

    Private webBrowser1 As New WebBrowser()
    Private WithEvents button1 As New Button()

    <STAThread()> _
    Public Shared Sub Main()
        Application.EnableVisualStyles()
        Application.Run(New Form1())
    End Sub

    Public Sub New()
        button1.Text = "call script code from client code"
        button1.Dock = DockStyle.Top
        webBrowser1.Dock = DockStyle.Fill
        Controls.Add(webBrowser1)
        Controls.Add(button1)
    End Sub

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _
        Handles Me.Load

        webBrowser1.AllowWebBrowserDrop = False
        webBrowser1.IsWebBrowserContextMenuEnabled = False
        webBrowser1.WebBrowserShortcutsEnabled = False
        webBrowser1.ObjectForScripting = Me
        ' Uncomment the following line when you are finished debugging.
        'webBrowser1.ScriptErrorsSuppressed = True

        webBrowser1.DocumentText = _
            "<html><head><script>" & _
            "function test(message) { alert(message); }" & _
            "</script></head><body><button " & _
            "onclick=""window.external.Test('called from script code')"" > " & _
            "call client code from script code</button>" & _
            "</body></html>"
    End Sub

    Public Sub Test(ByVal message As String)
        MessageBox.Show(message, "client code")
    End Sub

    Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles button1.Click

        webBrowser1.Document.InvokeScript("test", _
            New String() {"called from client code"})

    End Sub

End Class

编译代码Compiling the Code

此代码需要:This code requires:

  • 对 System 和 System.Windows.Forms 程序集的引用。

猜你喜欢

转载自blog.csdn.net/wqq1027/article/details/81127367