0

我有一个这样的脚本,一旦用户单击单选按钮,就会出现消息框。但是,当我单击“否”对话框结果时,消息框会出现两次。我不知道为什么会这样。我不希望它显示两次。我知道必须有一个非常简单的方法来解决这个问题。>.> 我也尝试返回函数,但没有运气。

 Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object,      ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged
         Dim result As Integer = MessageBox.Show("message", "caption",      MessageBoxButtons.YesNo)
         If result = DialogResult.No Then
             RadioButton1.Checked = False
         ElseIf result = DialogResult.Yes Then
             memoryh4x(&H160ED98, 1, 4)
         End If
     End Sub
4

1 回答 1

0

您更改 RadioButton Checked 属性,这会导致再次调用事件处理程序。

避免重新进入事件处理程序的最简单方法是通过全局变量

Dim inCheckedChanged As Boolean = False
......

Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object,      ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged
     Try
        ' If we could display the message box..... 
        if inCheckedChanged = False then
           ' Block the reexecution of the MessageBox when clicking NO
            inCheckedChanged = True
            Dim result As Integer = MessageBox.Show("message", "caption",      MessageBoxButtons.YesNo)
            If result = DialogResult.No Then
                ' Now, changing the property reenters the event handler 
                ' but the global variable prevents to get a second messagebox
                RadioButton1.Checked = False
            ElseIf result = DialogResult.Yes Then
                memoryh4x(&H160ED98, 1, 4)
            End If
         End If
    Finally
         InCheckedChanged = False
    End Try
 End Sub

请注意,我将所有内容都放在了 Try/Final 块中。这样,如果某事引发异常,全局变量 InCheckedChanged 在退出事件处理程序之前始终重置为 false

于 2015-02-28T20:00:31.290 回答