holmis83 holmis83 - 1 month ago 19
C# Question

Longpress in UWP

I'm porting an app to Univeral Windows Platform (Windows 10).

Android has a

event. Is there an equivalent for UWP?

I found there is a
Holding
event
which I tried to use something like this:

private void Rectangle_Holding(object sender, HoldingRoutedEventArgs e)
{
if (e.HoldingState == HoldingState.Started)
{
Debug.WriteLine("Holding started!");
}
}


Problem is the event is not triggered on Windows Desktop, when mouse is used instead of touch.

Answer

Mouse input doesn't produce Holding events by default, you should use RightTapped event to show the context menu, it is triggered when user long presses in a touch device and right clicks in a mouse device.

Take a look at GestureRecognizer.Holding and Detect Simple Touch Gestures, you can achieve that using the following code

public sealed partial class MainPage : Page
{
    GestureRecognizer gestureRecognizer = new GestureRecognizer();

    public MainPage()
    {
        this.InitializeComponent();
        gestureRecognizer.GestureSettings = Windows.UI.Input.GestureSettings.HoldWithMouse;         
    }

    void gestureRecognizer_Holding(GestureRecognizer sender, HoldingEventArgs args)
    {
        MyTextBlock.Text = "Hello";
    }

    private void Page_Loaded(object sender, RoutedEventArgs e)
    {
        gestureRecognizer.Holding += gestureRecognizer_Holding;
    }

    private void Grid_PointerPressed(object sender, PointerRoutedEventArgs e)
    {
        var ps = e.GetIntermediatePoints(null);
        if (ps != null && ps.Count > 0)
        {
            gestureRecognizer.ProcessDownEvent(ps[0]);
            e.Handled = true;
        }
    }

    private void Grid_PointerMoved(object sender, PointerRoutedEventArgs e)
    {
        gestureRecognizer.ProcessMoveEvents(e.GetIntermediatePoints(null));
        e.Handled = true;
    }

    private void Grid_PointerReleased(object sender, PointerRoutedEventArgs e)
    {
        var ps = e.GetIntermediatePoints(null);
        if (ps != null && ps.Count > 0)
        {
            gestureRecognizer.ProcessUpEvent(ps[0]);
            e.Handled = true;
            gestureRecognizer.CompleteGesture();
        }
    }
}
Comments