在 .net 示例中引发事件

Raising an event in .net example

我正在尝试创建一个在 vb.net 中引发事件的基本示例,我希望通过彻底研究它可以升级我的系统从串口接收数据的方式。

现在我有一个系统通过定时器从串行端口接收传入数据,问题是系统中的某些事件与我的定时器冲突。因此,我打算更改从串行端口接收数据的方式,而不是我想使用的计时器 vb.net raiseevent.

不幸的是,我找不到关于如何使用此事件的简单示例,通过彻底搜索,我看到了 MSDN 的 post 关于这个主题和 it is here.那么,我该如何使用这个例子呢?我试过像下面那样使用它

Public Event TimeExpired(ByVal Status As String)
Public Sub RaiseTimeExpiredEvent()
    RaiseEvent TimeExpired("Your time has run out")
    MessageBox.Show(TimeExpired())
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    RaiseTimeExpiredEvent()
End Sub

运行不正常,错误是

Error 1 'Public Event TimeExpired(Status As String)' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. C:\Users\Cary\Desktop\Projects\Testing\Testing\Testing\Form1.vb 5 25 Testing

因为那个错误,我试着这样做

Class Form1
Public Event TimeExpired(ByVal Status As String)
Public Sub RaiseTimeExpiredEvent()
    RaiseEvent TimeExpired("Your time has run out")
    MessageBox.Show(TimeExpired())

End Sub


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

结束Class

但错误指出

Error 2 Argument not specified for parameter 'Status' of 'Public Event TimeExpired(Status As String)'. C:\Users\Cary\Desktop\Projects\Testing\Testing\Testing\Form1.vb 11 9 Testing

您在使用 Visual Studio 吗?如果是,您可以尝试显示错误列表。为此,单击“查看”和“错误列表”。

Class Form1

    Public Event TimeExpired(Status As String)

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        RaiseEvent TimeExpired("Your time has run out")
    End Sub

End Class

要处理该事件,您可以添加:

Private Sub HandleTimeExpired(Status As String) Handles Me.TimeExpired
    MsgBox(Status)
End Sub

完整代码如下:

Class Form1

    Public Event TimeExpired(Status As String)

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        RaiseEvent TimeExpired("Your time has run out")
    End Sub

    Public Sub OnTimeExpired(Status As String) Handles Me.TimeExpired
        MsgBox(Status)
    End Sub

End Class

编辑:

如果你想在模块中移动事件的引发,你不能。您必须将其添加到 class 中。 See this link.

Class1 示例(您应该重命名...):

Public Class Class1

    Private Event TimeExpired(Status As String)

    Public Sub OnTimeExpired(Status As String)
        RaiseEvent TimeExpired(Status)
    End Sub

    Private Sub HandleTimeExpired(Status As String) Handles Me.TimeExpired
       MsgBox(Status)
    End Sub

End Class

要使用它,您必须在 Form1 中声明它 WithEvents :

Public Class Form1

    Dim WithEvents Class1 As New Class1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Class1.OnTimeExpired("Your time has run out")
    End Sub

End Class