1. 程式人生 > >webbrowser 控制元件實現WinForm與WebForm互動

webbrowser 控制元件實現WinForm與WebForm互動

 WebBrowser 控制元件可以讓你裝載Windows Form 應用程式中的 Web 網頁和其它採用瀏覽器的檔案。可以使用webbrowser 控制元件將現有的web框架控制項加入至 Windows Form 客戶端應用程式。
還是直接看程式碼吧。

WebBrowser 控制項 提供的屬性、方法和事件,可用來實現 Internet Explorer 的控制項
    webBrowser1.Navigate("www.cnblogs.com");    //將指定位置處的檔案載入至 WebBrowser

    
webBrowser1.GoBack();//上一頁
    webBrowser1.GoForward();//下一頁
    webBrowser1.Refresh();//重新整理
    webBrowser1.GoHome();//主頁
這裡提供了WebBrowser常用的方法,
    



上面的程式碼是將 我們園子的主頁載入到WebBrowser控制元件中。如果我們想要在應用程式中產生自己的網頁內容,可以設定DocumentText屬性。也可以通過Document屬性來處理目前的網頁內容。如下程式碼是使用 DocumentText 

屬性,顯示網頁內容。並用Document屬性來處理所顯示的網頁。

 1 private void btnDocumentText_Click(object sender, EventArgs e)
 2          {
 3            string szHtml = @"
 4
<HTML>
 5<HEAD>
 6<TITLE> DocumentText </TITLE>
 7</HEAD>
 8
 9<BODY>
10     Please enter your name:<br/>
11     <input type='text' name='Name'/><br/>
12    <a href='http://www.microsoft.com' >Send input to method of Form class</a>
13     
14</BODY>
15</HTML>";
16
17            webBrowser1.DocumentText = szHtml;
18          
19        }
20
21        private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
22        {
23            System.Windows.Forms.HtmlDocument document =  this.webBrowser1.Document;
24
25            if (document != null && document.All["Name"] != null && String.IsNullOrEmpty(document.All["Name"].GetAttribute("value")))
26            {
27                e.Cancel = true;
28                System.Windows.Forms.MessageBox.Show("You must enter your name before you can navigate to " +  e.Url.ToString());
29            }
30
31        }


既然我們可以通過DocumentText生成自己的網頁,那麼能不能象使用IE那樣操作這個網頁呢?,答案是肯定的,完全可以像操作Web程式那樣操作WebBrowser 控制項。比如我們可以加入指令碼,CSS。當然,如果你熟悉 HTML 物件物件模型 (DOM),也可以透過 Document 屬性來處理目前的Web網頁內容。下面的例子加入了JavaScript指令碼來控制網頁。如果要在Winfrom程式中寫大量的Javascriot程式碼,而且這些程式碼最終要轉換成String型載入到Webbrowser 那將是很痛苦的事情,不過沒有關係,我們可以建立一個js檔案,放入資源中,用的時候只需從資源中載入即可。這裡我建立一個名為 ClientScript.js 的檔案。

 1 <script language = "javascript">
 2 function ClickEvent(name)
 3 {
 4    alert("Hello: " +name);
 5}
 6
 7function KeyDown()
 8
 9    if (event.keyCode==116)
10    {
11         event.keyCode=0;
12         event.returnValue=false;
13    }
14  
15      return false;
16}

 

string szClientScript = ManagedWebBrowser.Properties.Resources.ResourceManager.GetString("ClientScript");

            string szWebBrowserText = "<html>" +
                "<head>" +
                "<title></title>"+                
                    szClientScript +
                 "</head>" +
               "<body onkeydown=\"KeyDown()\" oncontextmenu=\"event.returnValue=false\">"+
               
               "Please enter your name:<br/>"+
                 "<input type='text' name='Name'/><br/>"+
                 "<font onclick = 'ClickEvent(Name.value)'>Click Here</font>"+
                "</body></html>";


            webBrowser1.DocumentText = szWebBrowserText;

WebBrowser 是 System.Windows.Forms 下的控制項,也就是意味著它是用在WimForm程式下,那麼WebWrower所載入的Web頁面如何實現在WinForm程式下處理呢。例如上例中的 "<font onclick = 'ClickEvent(Name.value)'>Click Here</font>" 。這裡的Click事件是通過指令碼處理的,如何讓這個Click事件在Winform中處理呢?這裡要做一些修改。若要從指令碼存取使用者端應用程式,需要設定ObjectForScripting 屬性。指令碼可以將您指定的物件當做window.external 物件來存取。

使用ObjectForScripting屬性,可啟用 WebBrowser 控制項所裝載之 Web 網頁與包含 WebBrowser 控制項之應用程式間的通訊。
這個屬性可讓您整合動態超文字標記語言 (DHTML) 程式碼與使用者端應用程式程式碼。
指定給這個屬性的物件可讓 Web 網頁指令碼做為 window.external 物件,這個物件是為了存取主應用程式而提供的內建 DOM 物件。

 

 1  private void btnScriptEvent_Click(object sender, EventArgs e)
 2          {
 3
 4            // This is the handler for loading the script into the Web Browser control and allowing us to interact
 5            // between the script in the Browser control and this form class
 6
 7
 8            // Set the ObjectForScripting property of the Web Browser control to point to this form class
 9            // This will allow us to interact with methods in this form class via the window.external property 
10            webBrowser1.ObjectForScripting = this;
11
12            string szWebBrowserText = "<html>" +
13                "<head>" +
14                "<title></title>"+                    
15                 "</head>" +
16               "<body onkeydown=\"KeyDown()\" oncontextmenu=\"event.returnValue=false\">"+
17               
18               "Please enter your name:<br/>"+
19                 "<input type='text' name='Name'/><br/>"+
20                 "<font onClick='window.external.ClickEvent(Name.value)'>Click Here</font>"+
21                "</body></html>";
22
23
24            webBrowser1.DocumentText = szWebBrowserText;
25        }
26        public void ClickEvent(string userName)
27        {
28            // Simply echo out the name that the user typed in the input box of the HTML page
29            if (System.Threading.Thread.CurrentThread.CurrentUICulture.TextInfo.IsRightToLeft == true)
30                MessageBox.Show("Hello " + userName, "Managed Web Browser Sample", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading);
31            else
32                MessageBox.Show("Hello " + userName, "Managed Web Browser Sample", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
33
34        }

 


 這裡的ObjectForScripting 屬性設定為 this。注意:在From1 類的開頭加入了這麼一句[ComVisible(true)], 它在System.Runtime.InteropServices下,預設值為 true,指出 Managed 型別對於 COM 為可見的。

 [ComVisible(true)]
 public partial class Form1 : System.Windows.Forms.Form