Programing

웹 브라우저 컨트롤에 문자열 html 내용을 표시하는 방법은 무엇입니까?

crosscheck 2020. 12. 14. 07:52
반응형

웹 브라우저 컨트롤에 문자열 html 내용을 표시하는 방법은 무엇입니까?


AC # win 앱 프로그램이 있습니다. 내 데이터베이스에 html 형식으로 텍스트를 저장하지만 웹 브라우저에서 사용자에게 표시하고 싶습니다. 문자열 html 내용을 웹 브라우저 컨트롤에 표시하는 방법은 무엇입니까?

미리 감사드립니다


이 시도:

webBrowser1.DocumentText =
    "<html><body>Please enter your name:<br/>" +
    "<input type='text' name='userName'/><br/>" +
    "<a href='http://www.microsoft.com'>continue</a>" +
    "</body></html>";

Thomas W.의 설명대로-나는이 댓글을 거의 놓쳤지만 같은 문제가 있었기 때문에 대답으로 다시 쓸 가치가 있다고 생각합니다.

주요 문제는 webBrowser1.DocumentText일부 html에 대한 첫 번째 할당 후에 후속 할당이 효과가 없다는 것입니다.

Thomas가 링크 한 솔루션은 http://weblogs.asp.net/gunnarpeipman/archive/2009/08/15/displaying-custom-html-in-webbrowser-control.aspx 에서 자세히 찾을 수 있지만 아래에 요약하겠습니다. 나중에이 페이지를 사용할 수 없게 될 경우를 대비하여.

간단히 말해서, webBrowser 컨트롤이 작동하는 방식으로 인해 콘텐츠를 변경할 때마다 새 페이지로 이동해야합니다. 따라서 저자는 다음과 같이 컨트롤을 업데이트하는 방법을 제안합니다.

private void DisplayHtml(string html)
{
    webBrowser1.Navigate("about:blank");
    if (webBrowser1.Document != null)
    {
        webBrowser1.Document.Write(string.Empty);
    }
    webBrowser1.DocumentText = html;
}

그러나 현재 응용 프로그램에서 해당 줄에서 CastException이 발생한다는 것을 발견했습니다 if(webBrowser1.Document != null). 왜 그런지 모르겠지만 전체 if블록을 try catch로 감싸면 원하는 효과가 여전히 작동 한다는 것을 알았습니다 . 보다:

private void DisplayHtml(string html)
{
    webBrowser1.Navigate("about:blank");
    try
    {
        if (webBrowser1.Document != null)
        {
            webBrowser1.Document.Write(string.Empty);
        }
    }
    catch (CastException e)
    { } // do nothing with this
    webBrowser1.DocumentText = html;
}

따라서 함수 DisplayHtml가 실행될 때마다 CastException에서 메시지를 수신 if하므로 if 문의 내용에 도달하지 않습니다. 그러나을 if받지 않도록 문을 주석 처리 CastException하면 브라우저 컨트롤이 업데이트되지 않습니다. 예외가 발생한다는 사실에도 불구하고이 효과를 일으키는 Document 속성 뒤에있는 코드의 또 다른 부작용이 있다고 생각합니다.

어쨌든 이것이 사람들에게 도움이되기를 바랍니다.


공백으로 이동하는 대신 다음을 수행 할 수 있습니다.

webBrowser1.DocumentText="0";
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write(theHTML);
webBrowser1.Refresh();

이벤트 나 다른 것을 기다릴 필요가 없습니다. 내 프로젝트 중 하나에서 초기 DocumentText 할당을 테스트하고 작동하는 동안 MSDN 에서 OpenNew를 확인할 수 있습니다 .


어떤 이유로 m3z ( DisplayHtml(string)메소드 포함) 에서 제공하는 코드 가 제 경우에는 작동하지 않습니다 (처음 제외). 나는 항상 문자열에서 html을 표시하고 있습니다. 다음은 WebBrowser 컨트롤과의 전투 후 내 버전입니다.

webBrowser1.Navigate("about:blank");
while (webBrowser1.Document == null || webBrowser1.Document.Body == null)
    Application.DoEvents();
webBrowser1.Document.OpenNew(true).Write(html);

나를 위해 매번 일하고 있습니다. 누군가에게 도움이되기를 바랍니다.


내가 테스트 한 간단한 솔루션은

webBrowser1.Refresh();
var str = "<html><head></head><body>" + sender.ToString() + "</body></html>";
webBrowser1.DocumentText = str;

webBrowser.NavigateToString (yourString);


여기에 작은 코드가 있습니다. WebBrowser 컨트롤의 모든 후속 html 코드 변경에서 작동합니다. 특정 요구 사항에 맞게 조정할 수 있습니다.

    static public void SetWebBrowserHtml(WebBrowser Browser, string HtmlText)
    {
        if (Browser != null)
        {
            if (string.IsNullOrWhiteSpace(HtmlText))
            {
                // Putting a div inside body forces control to use div instead of P (paragraph)
                // when the user presses the enter button
                HtmlText = 
                        @"<html>
                    <head>
                    <meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"" />
                    </head>
                      <div></div>
                    <body>
                    </body>
                    </html>";
            }

            if (Browser.Document == null)
            {
                Browser.Navigate("about:blank");

                //Wait for document to finish loading
                while (Browser.ReadyState != WebBrowserReadyState.Complete)
                {
                    Application.DoEvents();
                    System.Threading.Thread.Sleep(5);
                }
            }

            // Write html code
            dynamic Doc = Browser.Document.DomDocument;
            Doc.open();
            Doc.write(HtmlText);
            Doc.close();


            // Add scripts here 
            /*  
            dynamic Doc = Document.DomDocument;
            dynamic Script = Doc.getElementById("MyScriptFunctions");
            if (Script == null)
            {
                Script = Doc.createElement("script");
                Script.id = "MyScriptFunctions";
                Script.text = JavascriptFunctionsSourcecode;
                Doc.appendChild(Script);
            }                 
            */



            // Enable contentEditable   
            /*  
            if (Browser.Document.Body != null)
            {
                if (Browser.Version.Major >= 9)
                    Browser.Document.Body.SetAttribute("contentEditable", "true");
            }             
             */

            // Attach event handlers
            // Browser.Document.AttachEventHandler("onkeyup", BrowserKeyUp);
            // Browser.Document.AttachEventHandler("onkeypress", BrowserKeyPress);
            // etc...
        }
    }        

오래된 질문이지만 여기에이 작업을 수행 할 방법이 있습니다.

If browser.Document IsNot Nothing Then
    browser.Document.OpenNew(True)
    browser.Document.Write(My.Resources.htmlTemplate)
Else
    browser.DocumentText = My.Resources.htmlTemplate
End If

그리고browser.Navigating 이벤트가 "about : blank"URL을 취소 하지 않는지 확인하십시오 . WebBrowser탐색의 전체 제어를위한 아래 예제 이벤트 .

Private Sub browser_Navigating(sender As Object, e As WebBrowserNavigatingEventArgs) Handles browser.Navigating

    Try
        Me.Cursor = Cursors.WaitCursor

        Select Case e.Url.Scheme

            Case Constants.App_Url_Scheme

                Dim query As Specialized.NameValueCollection = System.Web.HttpUtility.ParseQueryString(e.Url.Query)

                Select Case e.Url.Host

                    Case Constants.Navigation.URLs.ToggleExpander.Host

                        Dim nodeID As String = query.Item(Constants.Navigation.URLs.ToggleExpander.Parameters.NodeID)

                        :
                        :
                        <other operations here>
                        :
                        :

                End Select

            Case Else
                e.Cancel = (e.Url.ToString() <> "about:blank")

        End Select

    Catch ex As Exception
        ExceptionBox.Show(ex, "Operation failed.")
    Finally
        Me.Cursor = Cursors.Default
    End Try

End Sub

m3z에서 권장하는 DisplayHtml (string html)이 저에게 효과적이었습니다.

In case it helps somebody, I would also like to mention that initially there were some spaces in my HTML that invalidated the HTML and so the text appeared as a string. The spaces were introduced (around the angular brackets) when I pasted the HTML into Visual Studio. So if your text is still appearing as text after you try the solutions mentioned in this post, then it may be worth checking that the HTML syntax is correct.

참고URL : https://stackoverflow.com/questions/5362591/how-to-display-the-string-html-contents-into-webbrowser-control

반응형