VB.NET Windows 表单 - 如何在 form.close 之后防止代码从 运行 开始?

VB.NET Windows Forms - How to prevent code from running after form.close?

我有一个代码,我可以通过单击 form1 打开一个表单 (form2),然后遍历一个列表... 如果我有特定条件,我想关闭 form2... 然而,即使我用 'me.Close' 关闭表单,for 也会在列表的其余部分保持 运行

使用 'exit for'、'exit sub'、'return' 并不是我所需要的,因为在 for/sub 之后还有更多代码我不需要 运行.

示例代码:

Private Sub form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    AnyMethod()
    Msgbox("This message (1) isn't supposed to show AT ALL, yet it does")
End Sub

Private Sub AnyMethod()
    For i As Integer = 1 To 10
        If i = 4 Then
            Me.Close()
        End If
        Msgbox("This message (2) is supposed to show only four times")
    Next
    Msgbox("This message (3) isn't supposed to show AT ALL, yet it does")
End Sub

事件处理程序的其余部分已执行,因为您没有离开该方法。它是如此简单。您可以在 Me.Close()

之后使用 Exit Sub 离开该方法

调用Me.Close() 不会立即“删除”表单(和当前事件处理程序)。如果不再有对该表单的引用,垃圾收集器稍后将收集该表单。

另外 Closed 事件将被调用。

Me.Close() 只不过是常规方法调用,除非该方法抛出异常,否则您将停留在当前方法的上下文中。

如果您不想显示消息 1,您应该 return 来自 AnyMethod 的值。

Private Sub form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    If (AnyMethod()) Then
       Exit Sub
    End If
    Msgbox("This message (1) isn't supposed to show AT ALL, yet it does")
End Sub

Private Function AnyMethod() as Boolean
    For i As Integer = 1 To 10
        If i = 4 Then
            Me.Close()
            Return True
        End If
        Msgbox("This message (2) is supposed to show only four times")
    Next
    Msgbox("This message (3) isn't supposed to show AT ALL, yet it does")
    Return False
End Sub