How to get event type in a Sub handling multiple events?
I am creating a program using Visual Basic 2010开发者_开发百科 Express.
I want to make a Sub
handling both MouseHover
and MouseLeave
events. Is this possible? And if possible, how do I differ between MouseHover event and MouseLeave event?
Yes, the same method can handle multiple events, as long as they have compatible signatures. Since both the MouseHover
and MouseLeave
events have identical method signatures, this is easy.
By method signatures, of course, I mean the arguments that are passed in. For example, here are the signatures for a method that handles both of those events:
Sub MouseHoverHandler(ByVal sender As Object, ByVal e As System.EventArgs)
Sub MouseLeaveHandler(ByVal sender As Object, ByVal e As System.EventArgs)
Since those are identical, the same method can handle both events. All you have to do is add the names of both events after the Handles
keyword, separating them with a comma. For example:
Private Sub MegaHandler(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles myControl.MouseHover, myControl.MouseLeave
But, alas, that does make it impossible to distinguish between the events, as the same handler will be called for both. This is often convenient when you want to execute identical code and don't care which individual event was raised.
It is not a good option when you need to distinguish between the events. But there's absolutely nothing wrong with defining multiple event handler methods. It won't affect the performance of your application.
Another option you could consider is attaching stub methods as the handlers for both of those events, and have those stubs call out to another method that does the actual work. Because each event would have its own individual handler, you would be able to determine which event was raised, and pass that information as a parameter to your worker method. Maybe an explanation would be clearer:
Private Sub MouseHoverHandler(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles myControl.MouseHover
' Call the method that does the actual work
DoMouseWork(sender, e, True)
End Sub
Private Sub MouseLeaveHandler(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles myControl.MouseHover
' Call the method that does the actual work
DoMouseWork(sender, e, False)
End Sub
Private Sub MegaMouseHandler(ByVal sender As System.Object, ByVal e As System.EventArgs, _
ByVal isHover As Boolean)
' Do the appropriate work to handle the events here.
' If the isHover parameter is True, the MouseHover event was raised.
' If the isHover parameter is False, the MouseLeave event was raised.
End Sub
Bonus points for recognizing that specifying the type of event would be best implemented by passing an enum value to the mega-handler method, instead of a Boolean value. (Enums make your source code much more descriptive; you have to examine the signature of the MegaMouseHandler
method to know what the Boolean parameter represents.)
精彩评论