3
Public Event DocumentCompleted As WebBrowserDocumentCompletedEventHandler

Dim arg() As Object = {homeTeam, guestTeam}
        AddHandler browser.DocumentCompleted, New 
WebBrowserDocumentCompletedEventHandler(AddressOf DoStuff)

Private Sub DoStuff(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)

End Sub

触发 DocumentCompleted 事件时如何传递 homeTeam 和 guestTeam。我想将上述内容转换为 Dostuff 方法内部的值。

请帮忙。

4

1 回答 1

1

首先,你不能把它挂在不知名的地方:

Dim arg() As Object = {homeTeam, guestTeam}
AddHandler browser.DocumentCompleted,
           New WebBrowserDocumentCompletedEventHandler(AddressOf DoStuff)

AddHandler可能需要使用某种Initialize方法,可能是 inside Sub New、 afterInitializeComponent或 inside Form_Load,或者在您期望它被触发时(在特定事件之后)。请注意,您使用的是本机 .NET 组件的默认事件,具有默认事件类型。在这种情况下,您不能在触发时直接使用它已经提供的东西以外的任何东西。请参阅MSDN 上的 WebBrowser.DocumentCompleted 事件

但是,您可以覆盖所有相关类并拥有自己的 MyWebBrowser 控件和您自己的事件,其中将包含其他属性。请参见下面的示例:

Public Class Form1
  Sub New()
    ' This call is required by the designer.
    InitializeComponent()

    Dim browser As New MyWebBrowser
    AddHandler browser.MyDocumentCompleted, AddressOf DoStuff
  End Sub

  Private Sub DoStuff(ByVal sender As Object, ByVal e As MyWebBrowserDocumentCompletedArgs)
    Dim guestTeam As String = e.GuestTeam 'guest team
    Dim homeTeam As String = e.HomeTeam 'and home team are both accessible
    'so you can do some processing on them
  End Sub

  Public Class MyWebBrowserDocumentCompletedArgs : Inherits WebBrowserDocumentCompletedEventArgs
    Dim _homeTeam As String
    Dim _guestTeam As String
    Public ReadOnly Property HomeTeam
      Get
        Return _homeTeam
      End Get
    End Property
    Public ReadOnly Property GuestTeam
      Get
        Return _guestTeam
      End Get
    End Property

    Sub New(url As Uri, homeTeam As String, guestTeam As String)
      MyBase.New(url)
      _homeTeam = homeTeam
      _guestTeam = guestTeam
    End Sub
  End Class

  Public Class MyWebBrowser : Inherits WebBrowser
    Public Delegate Sub MyWebBrowserDocumentCompletedEventHandler(e As MyWebBrowserDocumentCompletedArgs)
    Public Event MyDocumentCompleted As MyWebBrowserDocumentCompletedEventHandler

    Protected Overrides Sub OnDocumentCompleted(e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs)
      MyBase.OnDocumentCompleted(e)
      'homeTeam and guestTeam need to be extracted from the current instance of MyWebBrowser, and passed further
      RaiseEvent MyDocumentCompleted(New MyWebBrowserDocumentCompletedArgs(e.Url, "homeTeam", "guestTeam"))
    End Sub
  End Class
End Class

如果您的项目相对较小,您确实可以将它们作为全局变量,正如@Vlad 在评论中所建议的那样。

于 2013-03-10T13:42:58.780 回答