Share via


HOW TO:實作 DHTML 程式碼和用戶端應用程式程式碼之間的雙向通訊

您可以使用 WebBrowser 控制項,將現有的動態超文字標記語言 (DHTML) Web 應用程式程式碼加入至 Windows Form 用戶端應用程式。 當您已經投入了大量的開發時間建立 DHTML 控制項,而且您想要不重寫現有程式碼就能享受到 Windows Form 豐富的使用者介面能力時,這項功能就非常有用。

WebBrowser 控制項可以讓您透過 ObjectForScriptingDocument 屬性,實作用戶端應用程式程式碼和 Web 網頁指令碼之間的雙向通訊。 此外,您可以設定 WebBrowser 控制項來隱藏 DHTML 實作,讓 Web 控制項和應用程式表單上的其他控制項完美地混用。 若要完美地混用這些控制項,請將顯示的頁面格式化,讓背景色彩和視覺化樣式符合表單上的其他部分,並使用 AllowWebBrowserDropIsWebBrowserContextMenuEnabledWebBrowserShortcutsEnabled 屬性來停用標準的瀏覽器功能。

若要將 DHTML 內嵌至 Windows Form 應用程式

  1. WebBrowser 控制項的 AllowWebBrowserDrop 屬性設定為 false,以防止 WebBrowser 控制項開啟放在控制項上的檔案。

    webBrowser1.AllowWebBrowserDrop = False
    
    webBrowser1.AllowWebBrowserDrop = false;
    
  2. 將控制項的 IsWebBrowserContextMenuEnabled 屬性設定為 false,以防止 WebBrowser 控制項在使用者以滑鼠右鍵按一下控制項時顯示捷徑功能表。

    webBrowser1.IsWebBrowserContextMenuEnabled = False
    
    webBrowser1.IsWebBrowserContextMenuEnabled = false;
    
  3. 將控制項的 WebBrowserShortcutsEnabled 屬性設定為 false,以防止 WebBrowser 控制項回應快速鍵。

    webBrowser1.WebBrowserShortcutsEnabled = False
    
    webBrowser1.WebBrowserShortcutsEnabled = false;
    
  4. 在表單的建構函式或 Load 事件處理常式中,設定 ObjectForScripting 屬性。

    下列程式碼使用表單類別本身做為指令碼物件。

    注意事項注意事項

    元件物件模型 (Component Object Model,COM) 必須要能夠存取指令碼物件。 若要讓 COM 看見您的表單,請將 ComVisibleAttribute 屬性 (Attribute) 加入至表單類別。

    webBrowser1.ObjectForScripting = Me
    
    webBrowser1.ObjectForScripting = this;
    
  5. 在應用程式程式碼中,實作指令碼會使用的公用屬性或方法。

    例如,如果您使用表單類別做為指令碼物件,請將下列程式碼加入至表單類別。

    Public Sub Test(ByVal message As String)
        MessageBox.Show(message, "client code")
    End Sub
    
    public void Test(String message)
    {
        MessageBox.Show(message, "client code");
    }
    
  6. 在指令碼中使用 window.external 物件來存取指定物件的公用屬性和方法。

    下列 HTML 程式碼示範如何按一下按鈕來呼叫指令碼物件上的方法。 將這段程式碼複製到您使用控制項的 Navigate 方法載入或指派給控制項 DocumentText 屬性的 HTML 文件的 BODY 項目中。

    <button onclick="window.external.Test('called from script code')">
        call client code from script code
    </button>
    
  7. 實作應用程式程式碼要使用的指令碼函式。

    下列 HTML SCRIPT 項目提供一個範例函式。 將這段程式碼複製到您使用控制項的 Navigate 方法載入或指派給控制項 DocumentText 屬性的 HTML 文件的 HEAD 項目中。

    <script>
    function test(message) { 
        alert(message); 
    }
    </script>
    
  8. 使用 Document 屬性,從用戶端應用程式程式碼存取指令碼。

    例如,將下列程式碼加入至按鈕 Click 事件處理常式。

    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 控制項顯示關於指令碼問題的錯誤訊息。

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

範例

在下列這個完整的程式碼範例中,將會提供一個示範應用程式,讓您用來瞭解這項功能。 此 HTML 程式碼是透過 DocumentText 屬性載入至 WebBrowser 控制項,而不是從另一個 HTML 檔案載入。

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
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" });
    }

}

編譯程式碼

這個程式碼需要:

  • System 和 System.Windows.Forms 組件的參考。

如需從 Visual Basic 或 Visual C# 的命令列建置這個範例的詳細資訊,請參閱從命令列建置 (Visual Basic)使用 csc.exe 建置命令列。 您也可以透過將程式碼貼入新的專案,在 Visual Studio 中建置此範例。 如需詳細資訊,請參閱HOW TO:使用 Visual Studio 編譯及執行完整的 Windows Form 程式碼範例HOW TO:使用 Visual Studio 編譯及執行完整的 Windows Form 程式碼範例HOW TO:使用 Visual Studio 編譯及執行完整的 Windows Form 程式碼範例HOW TO:使用 Visual Studio 編譯及執行完整的 Windows Form 程式碼範例如何:使用 Visual Studio 編譯及執行完整的 Windows Form 程式碼範例.

請參閱

參考

WebBrowser

WebBrowser.Document

WebBrowser.ObjectForScripting

其他資源

WebBrowser 控制項 (Windows Form)