gpt4 book ai didi

.net - 在 .net 示例中引发事件

转载 作者:行者123 更新时间:2023-12-03 23:24:08 25 4
gpt4 key购买 nike

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

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

不幸的是,我找不到关于如何使用此事件的简单示例,通过彻底搜索,我看到了 MSDN 的 发布有关此主题和 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

结束类

但是错误状态

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

编辑:

如果你想在一个模块中移动事件的提升,你不能。你必须将它添加到一个类中。 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

关于.net - 在 .net 示例中引发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31844952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com