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.

Kate Gregory
  • 18,808
  • 8
  • 56
  • 85
kartal
  • 17,436
  • 34
  • 100
  • 145
  • 2
    There is sample code [here](http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.uielement.pointerpressed) – Carey Gregory Dec 16 '12 at 18:52

3 Answers3

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
        }
    }
}
andrewpey
  • 650
  • 3
  • 11
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
    }
}
Mattias Josefsson
  • 1,147
  • 1
  • 7
  • 22
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.

AntiqTech
  • 717
  • 1
  • 6
  • 10
  • 1
    This applied to me, because I was using the `PointerReleased` event instead of the `PointerPressed` event that other answers use. – Felix Jan 02 '22 at 23:21