我有一个这样的脚本,一旦用户单击单选按钮,就会出现消息框。但当我点击"否"拨号结果时,消息框会出现两次。我不知道为什么会发生这种事。我不希望它显示两次。我知道一定有一个简单的方法可以解决这个问题我也试着返回函数,但没有成功。
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
您更改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/Finally块中。通过这种方式,如果有东西抛出异常,全局变量InCheckedChanged在从事件处理程序退出之前总是重置为false