다음을 통해 공유


방법: DHTML 코드와 클라이언트 애플리케이션 코드 간의 양방향 통신 구현

WebBrowser 컨트롤을 사용하여 Windows Forms 클라이언트 애플리케이션에 기존 DHTML(동적 HTML) 웹 애플리케이션 코드를 추가할 수 있습니다. DHTML 기반 컨트롤을 만드는 데 상당한 개발 시간을 투자했으며 기존 코드를 다시 작성할 필요 없이 Windows Forms의 풍부한 사용자 인터페이스 기능을 활용하려는 경우에 유용합니다.

WebBrowser 컨트롤을 사용하면 ObjectForScriptingDocument 속성을 통해 클라이언트 애플리케이션 코드와 웹 페이지 스크립팅 코드 간의 양방향 통신을 구현할 수 있습니다. 또한 웹 컨트롤이 애플리케이션 폼의 다른 컨트롤과 매끄럽게 혼합되어 해당 DHTML 구현을 숨기도록 WebBrowser 컨트롤을 구성할 수 있습니다. 컨트롤을 매끄럽게 혼합하려면 배경색 및 시각적 스타일이 폼의 나머지 부분과 일치하도록 표시되는 페이지 형식을 지정하고 AllowWebBrowserDrop, IsWebBrowserContextMenuEnabledWebBrowserShortcutsEnabled 속성을 통해 표준 브라우저 기능을 사용하지 않도록 설정합니다.

Windows Forms 애플리케이션에 DHTML을 포함하려면

  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. 양식의 생성자의 ObjectForScripting 속성을 설정하거나 OnLoad 메서드를 재정의합니다.

    다음 코드에서는 스크립팅 개체에 대한 폼 클래스 자체를 사용합니다.

    webBrowser1.ObjectForScripting = new MyScriptObject(this);
    
    webBrowser1.ObjectForScripting = New MyScriptObject(Me)
    
  5. 스크립팅 개체를 구현합니다.

    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. 스크립팅 코드에서 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 코드는 별도 HTML 파일에서 로드되지 않고 DocumentText 속성을 통해 WebBrowser 컨트롤에 로드됩니다.

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

코드 컴파일

이 코드에는 다음이 필요합니다.

  • System 및 System.Windows.Forms 어셈블리에 대한 참조

참고 항목