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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, the same method can handle multiple events, as long as they have compatible signatures. Since both the
MouseHoverandMouseLeaveevents 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:
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
Handleskeyword, separating them with a comma. For example: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:
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
MegaMouseHandlermethod to know what the Boolean parameter represents.)