PointerPressed: left or right button?
Asked Answered
R

3

12

How can I get the type of pressed pointer (left mouse down or right mouse down) in a Metro style C# app? I didn't find a MouseLeftButtonDown event handler in any Metro style UI element. I should use PointerPressed event instead, but I don't know how can i get which button was pressed.

Retentive answered 16/12, 2012 at 18:50 Comment(1)
There is sample code hereEvangelical
D
17

PointerPressed is enough to handle mouse buttons:

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
        }
    }
}
Detriment answered 16/12, 2012 at 20:3 Comment(2)
I have a UWP app and when adding a handler to a MousePressed event, it gets fired only on mouse right click.Tonnage
For WinUI3 and UWP, the PointerDeviceType is Microsoft.UI.Input.PointerDeviceType.MousePearce
G
3

You can use the following event to determine what pointer is used and what button is pressed.

private void Target_PointerMoved(object sender, PointerRoutedEventArgs e)
{
    Windows.UI.Xaml.Input.Pointer ptr = e.Pointer;
    Windows.UI.Input.PointerPoint ptrPt = e.GetCurrentPoint(Target);

    if (ptrPt.Properties.IsLeftButtonPressed)
    {
        //Do stuff
    }
    if (ptrPt.Properties.IsRightButtonPressed)
    {
        //Do stuff
    }
}
Gailgaile answered 16/12, 2012 at 19:56 Comment(0)
P
2

Working on a UWP project and previous answers like Properties.IsLeftButtonPressed/IsRightButtonPressed did not work for me. Those values are always false. I realized during the Debugging that Properties.PointerUpdateKind was changing according to mouse button. Here is the result which worked for me:

var properties = e.GetCurrentPoint(this).Properties;
if (properties.PointerUpdateKind == Windows.UI.Input.PointerUpdateKind.LeftButtonReleased)
{

}
else if (properties.PointerUpdateKind == Windows.UI.Input.PointerUpdateKind.RightButtonReleased)
{

}
else if (properties.PointerUpdateKind == Windows.UI.Input.PointerUpdateKind.MiddleButtonReleased)
{

}

There are more options in PointerUpdateKind like ButtonPressed varities of the ones in the example and XButton varities e.g. XButton1Pressed, XButton2Released etc.

Phobos answered 12/7, 2019 at 22:42 Comment(1)
This applied to me, because I was using the PointerReleased event instead of the PointerPressed event that other answers use.Kowloon

© 2022 - 2024 — McMap. All rights reserved.