我怎么知道在VBnet中的图片框中触发了什么事件?
在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 。我这样做的原因是为了使代码根据使用的对象进行更多分类。
答案 0 :(得分:3)
你可以做的一件事是创建一个辅助函数,它可以使用一个额外的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
修改强>
如前所述,Reflection是一种可能性,虽然由于涉及的开销量很大而不理想(特别是在像这样的事件可以被频繁调用的情况下)。话虽这么说,我用反射简单地说明了它是可能的。 (实际上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