How to determine which event called a handler when multiple events are assigned to it?

67 views Asked by At

Lets say I assign one handler to two events like this:

<Canvas PointerPressed="Handler" PointerMoved="Handler"/>

And I have the Handler as:

void Handler(object sender, PointerRoutedEventArgs e) {
    /*
     
    */
}

How do I know from inside Handler which particular event (PointerMoved or PointerPressed) triggered it ?

1

There are 1 answers

2
jarmanso7 On BEST ANSWER

The second parameter EventArgs should have a type corresponding to the particular event the handler is attached to. Therefore, you can determine which event an eventhandler belongs to just by looking at the type of the second parameter.

The EventHandler is in reality a delegate (see this). Your handler method signature has to match (including the type of the parameters) with that delegate's signature, so I don't think you can subcribe to PointerMoved and PointerPressed events with void Handler(object sender, PointerRoutedEventArgs e) in the first place.

If you are trying to figure out to which event a particular handler is called from between two EventHandlers of the same type, then your best bet is to look at the first parameter sender. As the name implies, this is a reference to the object that raised the event itself.


UPDATE: Sorry, I didn't realize both events do indeed use the same type PointerRoutedEventArgs:

The static PointerPoint methods, GetCurrentPoint and GetIntermediatePoints, always use the context of the app. The PointerRoutedEventArgs event data class is used for these events:

PointerPressed, PointerCanceled, PointerCaptureLost, PointerEntered, PointerExited, PointerMoved, PointerReleased, PointerWheelChanged.

so it's not an option for you to look at the type of the EventArgs argument. As another user said in the comments, it's strange to use the same handler for different events in the first place. In such case, you'd probably need to go case by case, and see what properties of PointedRouterEventArgs are relevant to each of the possible events. For example, as shown in this answer, you could check the properties IsRightButtonPressed and IsLeftButtonPressed of e.GetCurrentPoint(this) to determine if the raised event was a PointerPressed or a different one. And the same idea with other properties in the EventArgs parameter particularly relevant to PointerMoved:

void MainPage_PointerPressed(object sender, PointerRoutedEventArgs e)
{
    // Check for input device
    if (e.Pointer.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Mouse)
    {
        var properties = e.GetCurrentPoint(this).Properties;
        if (properties.IsLeftButtonPressed)
        {
            // Left button pressed
        }
        else if (properties.IsRightButtonPressed)
        {
            // Right button pressed
        }
    }
}