0

在 VB.NET 中,为什么不触发以下自定义事件?

Public Class classes1
    Public Event buttonload(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Protected Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)        Handles Button2.Click
        attd.Show()
        RaiseEvent buttonload(sender, e)
    End Sub
End Class

Public Class attd
    Dim WithEvents c1 As New classes1
    Sub c1_buttonload(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles c1.buttonload
        MsgBox("Event received")
    End Sub
End Class
4

1 回答 1

1

您正在使用您的第一个表单 ,classes1来显示您的第二个表单,attd,然后引发您的 CustomEvent。然后在您的第二个表单中attd,您正在创建第一个表单的另一个实例,classes1然后尝试将您的处理程序附加到该实例的事件。它们不一样,所以它不会着火。

真的不清楚你到底想做什么。如果你只是在试验一些事件,你可以尝试这样的事情。

表格1

Public Class Form1
    Dim attd As Form2 = New Form2
    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        attd.Show()
    End Sub

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        AddHandler attd.buttonload, AddressOf buttonLoadHandler
    End Sub

    Private Sub buttonLoadHandler(sender As Object, e As EventArgs)
        MsgBox("Event received")
    End Sub

End Class

表格2

Public Class Form2
    Public Event buttonload(ByVal sender As System.Object, ByVal e As System.EventArgs)

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        RaiseEvent buttonload(sender, e)
    End Sub
End Class

如果您只是想让您的第二个表单响应第一个表单按钮单击,请尝试这样的操作。

表格1

Public Class Form1
    Dim attd As Form2 = New Form2
    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        attd.Show()
        attd.showMessageBox()
    End Sub

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

    End Sub
End Class

表格2

Public Class Form2
    Public Sub showMessageBox()
        MsgBox("Hello World")
    End Sub
End Class
于 2013-02-04T04:13:59.207 回答