다음을 통해 공유


방법: DHTML 코드와 클라이언트 응용 프로그램 코드 간의 양방향 통신 구현

업데이트: 2007년 11월

WebBrowser 컨트롤을 사용하면 기존의 DHTML(동적 HTML) 웹 응용 프로그램 코드를 Windows Forms 클라이언트 응용 프로그램에 추가할 수 있습니다. 이는 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. 폼의 생성자나 Load 이벤트 처리기에서 ObjectForScripting 속성을 설정합니다.

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

    참고:

    COM(구성 요소 개체 모델)은 스크립팅 개체에 액세스할 수 있어야 합니다. COM에서 폼을 볼 수 있도록 하려면 ComVisibleAttribute 특성을 폼 클래스에 추가합니다.

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

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에서 코드를 새 프로젝트에 붙여넣어 이 예제를 빌드할 수도 있습니다.

참고 항목

참조

WebBrowser

WebBrowser.Document

WebBrowser.ObjectForScripting

기타 리소스

WebBrowser 컨트롤(Windows Forms)