Aracılığıyla paylaş


Nasıl Yapılır: DHTML Kodu ile İstemci Uygulama Kodu Arasında Two-Way İletişimini Gerçekleştirmek

Windows Forms istemci uygulamalarınıza mevcut dinamik HTML (DHTML) Web uygulaması kodunu eklemek için denetimi kullanabilirsiniz WebBrowser . Bu, DHTML tabanlı denetimler oluşturmak için önemli bir geliştirme süresi ayırdığınızda ve var olan kodu yeniden yazmak zorunda kalmadan Windows Forms'un zengin kullanıcı arabirimi özelliklerinden yararlanmak istediğinizde kullanışlıdır.

Denetim, WebBrowser özellikleri aracılığıyla, istemci uygulamanızın kodu ile Web sayfası betik kodunuz arasında iki yönlü iletişimi uygulamanıza olanak tanır. Ayrıca, Web denetimlerinizin uygulama formunuzda diğer denetimlerle sorunsuz bir şekilde karışması ve DHTML uygulamalarını gizlemesi için denetimi yapılandırabilirsiniz WebBrowser . Denetimleri sorunsuz bir şekilde karıştırmak için, görüntülenen sayfayı arka plan rengi ve görsel stili formun geri kalanıyla eşleşecek şekilde biçimlendirin ve standart tarayıcı özelliklerini devre dışı bırakmak için , AllowWebBrowserDropve IsWebBrowserContextMenuEnabled özelliklerini kullanınWebBrowserShortcutsEnabled.

Windows Forms uygulamanıza DHTML eklemek için

  1. Denetimin WebBrowserAllowWebBrowserDrop üzerine bırakılan dosyaları açmasını önlemek için denetimin false özelliğini WebBrowser olarak ayarlayın.

    webBrowser1.AllowWebBrowserDrop = false;
    
    webBrowser1.AllowWebBrowserDrop = False
    
  2. Kullanıcı sağ tıkladığında denetimin IsWebBrowserContextMenuEnabledfalse kısayol menüsünü görüntülemesini önlemek için denetimin özelliğini WebBrowser olarak ayarlayın.

    webBrowser1.IsWebBrowserContextMenuEnabled = false;
    
    webBrowser1.IsWebBrowserContextMenuEnabled = False
    
  3. Denetimin WebBrowserShortcutsEnabled kısayol tuşlarına yanıt vermesini önlemek için denetimin false özelliğini WebBrowser olarak ayarlayın.

    webBrowser1.WebBrowserShortcutsEnabled = false;
    
    webBrowser1.WebBrowserShortcutsEnabled = False
    
  4. Formun ObjectForScripting özelliği ayarlayın veya OnLoad yöntemini geçersiz kılın.

    Aşağıdaki kod, script nesnesi için form sınıfının kendisini kullanır.

    webBrowser1.ObjectForScripting = new MyScriptObject(this);
    
    webBrowser1.ObjectForScripting = New MyScriptObject(Me)
    
  5. Betik nesnenizi uygulayın.

    public class MyScriptObject
    {
        private Form1 _form;
    
        public MyScriptObject(Form1 form)
        {
            _form = form;
        }
    
        public void Test(string message)
        {
            MessageBox.Show(message, "client code");
        }
    }
    
    Public Class MyScriptObject
        Private _form As Form1
    
        Public Sub New(ByVal form As Form1)
            _form = form
        End Sub
    
        Public Sub Test(ByVal message As String)
            MessageBox.Show(message, "client code")
        End Sub
    
    End Class
    
  6. Belirtilen nesnenin genel özelliklerine ve yöntemlerine erişmek için betik kodunuzda window.external nesnesini kullanın.

    Aşağıdaki HTML kodu, bir düğme tıklamasından betik nesnesi üzerinde bir yöntemin nasıl çağrılduğunu gösterir. Bu kodu, denetimin Navigate yöntemini kullanarak yüklediğiniz ya da denetimin DocumentText özelliğine atadığınız bir HTML belgesinin BODY öğesine kopyalayın.

    <button onclick="window.external.Test('called from script code')">
        call client code from script code
    </button>
    
  7. Uygulama kodunuzun kullanacağı komut dosyası kodunda işlevler uygulayın.

    Aşağıdaki HTML BETIĞI öğesi örnek bir işlev sağlar. Bu kodu, denetimin Navigate yöntemini kullanarak yüklediğiniz veya denetimin DocumentText özelliğine atadığınız bir HTML belgesinin HEAD öğesine kopyalayın.

    <script>
    function test(message) {
        alert(message);
    }
    </script>
    
  8. İstemci uygulama kodunuzdan betik koduna erişmek için Document özelliğini kullanın.

    Örneğin, aşağıdaki kodu bir düğme Click olay işleyicisine ekleyin.

    webBrowser1.Document.InvokeScript("test",
        new String[] { "called from client code" });
    
    webBrowser1.Document.InvokeScript("test", _
        New String() {"called from client code"})
    
  9. DHTML'nizde hata ayıklamayı bitirdiğinizde, denetimin ScriptErrorsSuppressed özelliğini true olarak ayarlayın; bu, WebBrowser denetiminin betik kodu sorunları için hata iletilerini görüntülemesini önler.

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

Örnek

Aşağıdaki tam kod örneği, bu özelliği anlamak için kullanabileceğiniz bir tanıtım uygulaması sağlar. HTML kodu ayrı bir HTML dosyasından yüklenmek yerine WebBrowser özelliği aracılığıyla DocumentText denetime yüklenir.

using System;
using System.Windows.Forms;

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

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        webBrowser1.AllowWebBrowserDrop = false;
        webBrowser1.IsWebBrowserContextMenuEnabled = false;
        webBrowser1.WebBrowserShortcutsEnabled = false;
        webBrowser1.ObjectForScripting = new MyScriptObject(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>";
    }

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

public class MyScriptObject
{
    private Form1 _form;

    public MyScriptObject(Form1 form)
    {
        _form = form;
    }

    public void Test(string message)
    {
        MessageBox.Show(message, "client code");
    }
}
Imports System.Windows.Forms

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

    Protected Overrides Sub OnLoad(e As EventArgs)
        MyBase.OnLoad(e)

        webBrowser1.AllowWebBrowserDrop = False
        webBrowser1.IsWebBrowserContextMenuEnabled = False
        webBrowser1.WebBrowserShortcutsEnabled = False
        webBrowser1.ObjectForScripting = New MyScriptObject(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

    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

Public Class MyScriptObject
    Private _form As Form1

    Public Sub New(ByVal form As Form1)
        _form = form
    End Sub

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

End Class

Kodu Derleme

Bu kod şunları gerektirir:

  • System ve System.Windows.Forms derlemelerine referanslar.

Ayrıca bakınız