我们怎么知道在VBnet的picturebox里触发了什么事件

问题描述:

我怎么知道在VBnet的picturebox里触发了什么事件?我们怎么知道在VBnet的picturebox里触发了什么事件

在vbnet代码

Private Sub picButton_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles picButton.MouseEnter 
    'CODE HERE' 
End Sub 

Private Sub picButton_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles picButton.MouseLeave 
    'CODE HERE' 
End Sub 

,我想使它像这样:

Private Sub picButtonEVent(ByVal sender As Object, ByVal e As System.EventArgs) Handles picButton.MouseLeave, picButton.MouseEnter 
    'CODE HERE' 
    'If MouseEnter Then' 
     'Code for mouseEnter' 
    'ElseIf MouseLeave Then' 
     'Code for mouseLeave' 
    'End If' 
End Sub 

我想知道是什么触发事件是否是.MouseEnter.MouseLeave。我之所以这样做是为了根据所使用的对象使代码更加分类。

你可以做的一件事是创建一个辅助函数,该函数接受一个额外的Enum参数,用于确定事件类型,然后您可以将虚拟事件放在一个区域中,以便可以折叠它们。离手,我不知道一个优雅的方式来确定哪些事件实际上从事件本身的方式触发(即不使用反射...)

我的建议:

Private Sub picButton_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles picButton.MouseEnter 
    UniversalEvent(this, e, EventType.MouseEnter) 
End Sub 

Private Sub picButton_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles picButton.MouseLeave 
    UniversalEvent(this, e, EventType.MouseLeave) 
End Sub 

Private Sub UniversalEvent(ByVal sender As Object, ByVal e As System.EventArgs, ByVal eventType As EventType) 
    If MouseEnter Then 
     'Code for mouseEnter' 
    ElseIf MouseLeave Then 
     'Code for mouseLeave' 
    End If' 
End Sub 

编辑:

如前所述,反射是一种可能性,尽管由于涉及的开销很大(尤其是在像这些可能被频繁调用的事件的情况下)并不理想。话虽如此,我用“反思”简单地举了一个实例来说明这是可能的。 (其实StackTrace,这是我用过的东西,是在System.Diagnostics。不完全Reflection但是这对我来说足够接近...)

Please don't send the raptors...

Public Class Form1 

    Private Sub PictureBox_Events(ByVal sender As System.Object, ByVal e As System.EventArgs) _ 
     Handles PictureBox1.MouseLeave, PictureBox1.MouseEnter 

     Select Case GetEventType(New StackTrace()) 
      Case EventType.MouseEnter 
       Console.WriteLine("Enter") 
      Case EventType.MouseLeave 
       Console.WriteLine("Leave") 
      Case Else 
       Console.WriteLine("Dunno") 
     End Select 

    End Sub 

    Private Function GetEventType(ByRef callStack As StackTrace) As EventType 
     'I laugh in the face of NullReferenceExceptions...' 
     Dim callerName As String = callStack.GetFrames()(1).GetMethod().Name 

     If "OnMouseEnter".Equals(callerName, StringComparison.OrdinalIgnoreCase) Then 
      Return EventType.MouseEnter 
     ElseIf "OnMouseLeave".Equals(callerName, StringComparison.OrdinalIgnoreCase) Then 
      Return EventType.MouseLeave 
     End If 

     Return EventType.Dunno 

    End Function 

    Enum EventType 
     Dunno 
     MouseEnter 
     MouseLeave 
    End Enum 

End Class 
+1

我还补充说,尽管大多数事件有'é '从EventArgs'继承,相当多的事件有更详细的事件信息 - 所以你可以按照上面描述的做,但没有一些讨厌的DirectCast(),你将失去事件的任何额外信息 – Basic 2010-12-20 04:11:38

+0

好点, 谢谢! – Pwninstein 2010-12-20 04:38:41