随机调用事件



我想调用一个随机的PictureBoxN_Click事件。我如何在vb.net中做到这一点?

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
If ListView1.Items.Count > 0 Then
If IsNothing(Me.ListView1.FocusedItem) Then
ListView1.TopItem.Selected = True
End If
For Each file As ListViewItem In ListView1.Items
Dim filePath As String = file.SubItems(1).Text & "" & file.Text
If file.Selected = True Then
Process.Start(filePath)
End If
Next
Else
Dim rndm As Integer = CInt(Math.Ceiling(Rnd() * 20)) + 1
Dim rndpic As String = "PictureBox" & rndm & "_Click"
Call rndpic(Nothing, Nothing)
End If
End Sub

虽然我同意jmcilinney的回答,但以下是如何实现您最初的要求。请注意,这还向您展示了如何使用Controls.Find()"按名称"获得对所需PictureBox的引用

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Static R As New Random
Dim rndm As Integer = R.Next(1, 91) ' <-- return a value between 1 and 90 inclusive (yes, 91 is correct!)
Dim ctlName As String = "PictureBox" & rndm.ToString
Dim methodName As String = ctlName & "_Click"
Dim flags As Reflection.BindingFlags = Reflection.BindingFlags.IgnoreCase Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic
Dim MI As _MethodInfo = Me.GetType.GetMethod(methodName, flags)
If Not IsNothing(MI) Then
Dim matches() As Control = Me.Controls.Find(ctlName, True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is PictureBox Then
Dim pb As PictureBox = DirectCast(matches(0), PictureBox)
MI.Invoke(Me, New Object() {pb, New EventArgs})
End If
End If
End Sub

首先,您没有调用事件。事件是由您提出的,而不是由您提出。在PictureBox上引发Click事件的唯一简单方法是用鼠标单击它。

你所说的是调用一个方法。事件处理程序不是事件。事件处理程序是一种在引发事件时自动执行的方法。直接调用事件处理程序是一种非常糟糕的做法。

您应该做的是将要执行的代码放入其自己的方法中,该方法具有类型为PictureBox的参数。然后,您可以从PictureBoxesClick事件处理程序以及您想要的任何其他地方调用该方法。如果你这样做,那么在这种情况下,你甚至不必考虑任何Click事件,这就是应该的,因为没有点击

如果对每个PictureBox执行相同的操作,那么所有PictureBoxes应该只有一个事件处理程序。如果要在单击Button时执行随机PictureBox的代码,则可以选择一个随机PictureBox并将其传递给方法。例如

Private rng As New Random
Private Sub PictureBoxes_Click(sender As Object, e As EventArgs) Handles PictureBox3.Click,
   PictureBox2.Click,
   PictureBox1.Click
'Prcoess the PictureBox that was clicked.
ProcessPictureBox(DirectCast(sender, PictureBox))
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Process a random PictureBox.
Dim pictureBoxes = {PictureBox1, PictureBox2, PictureBox3}
Dim pictureBox = pictureBoxes(rng.Next(pictureBoxes.Length))
ProcessPictureBox(pictureBox)
End Sub
Private Sub ProcessPictureBox(pictureBox As PictureBox)
'Use pictureBox here.
End Sub

相关内容

  • 没有找到相关文章

最新更新