天天看點

WinForm中使用WebBrowser

 使用 WebBrowser 控件,可以通過 ObjectForScripting 和 Document 屬性在用戶端應用程式代碼和網頁腳本代碼之間實作雙向通信。此外,可以對 WebBrowser 控件進行配置,使 Web 控件可以與應用程式窗體上的其他控件進行無縫整合,進而隐藏其 DHTML 實作。

示例:

WinForm中使用WebBrowser

背景:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Security.Permissions;

namespace A

{

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]

    [System.Runtime.InteropServices.ComVisibleAttribute(true)]

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)

        {

            webBrowser1.AllowWebBrowserDrop = false;

            webBrowser1.IsWebBrowserContextMenuEnabled = false;

            webBrowser1.WebBrowserShortcutsEnabled = false;

            webBrowser1.ScriptErrorsSuppressed = true;

        }

        public string InvokeFormMethod(string message)

        {

            MessageBox.Show(message);

            return "Charles2008";

        }

        private void btnTest_Click(object sender, EventArgs e)

        {

            this.webBrowser1.Document.InvokeScript("msgalert",new string[]{"Called Javascript code"});

        }

        private void btnView_Click(object sender, EventArgs e)

        {

            this.webBrowser1.Navigate(this.textBox1.Text);

            this.webBrowser1.ObjectForScripting = this;

        }

    }

}

New1.htm代碼:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>

 <head>

  <title></title>

  <script type="text/javascript">

      function msgalert(msg) {

          alert(msg);

      }

  </script>

 </head>

 <body>

     <input type="button" title="Html調用Winform中的方法" value="HTML調用Winform中得方法" οnclick="alert(window.external.InvokeFormMethod('123'))" />

 </body>

</html>

運作結果:

WinForm中使用WebBrowser

繼續閱讀