使用WebBrowser 控件,可以通過 ObjectForScripting 和Document 
屬性在客戶端應用程序代碼和網頁腳本代碼之間實現雙向通信



'宣告


Public Property ObjectForScripting As Object
'用途

Dim instance As WebBrowser
Dim value As Object

value = instance.ObjectForScripting

instance.ObjectForScripting = value

 

 

 

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

您可以將這個屬性設為任意 COM-Visible 物件,以讓指令碼可以使用這個物件的公用屬性和方法。您可以使用 ComVisibleAttribute 標記類別,以讓該類別 COM-Visible。

若要從用戶端應用程式程式碼呼叫 Web 網頁中所定義的函式,請使用可從 Document 屬性中擷取之 HtmlDocument 物件的 HtmlDocument.InvokeScript 方法。

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

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 pcman 的頭像
    pcman

    電腦購物天堂

    pcman 發表在 痞客邦 留言(0) 人氣()