Khalil Khalaf
Khalil Khalaf

Reputation: 9397

How can I combine Touch and Mouse Event Handlers without producing duplicate behavior?

I am working on a WPF application which is being used on a Touch Screen Tablet. I develop using VS2015 IDE and I use my Mouse to debug.

I must handle buttons' down and up events to execute certain tasks. I use PreviewMouse and PreviewTouch event handlers and I have a problem in every case I use:

I want something similar to this Prevent a WPF application to interpret touch events as mouse events but only on the tablet. I still need to use my mouse in my environment. How can I fix that?

Button sample XAML:

<Button x:Name="locationScrollUpButton" Margin="0,5,5,0" Background="Transparent" Padding="0" Grid.Row="1" Grid.Column="1" PreviewMouseUp="locationScrollUpButton_PreviewMouseUp" PreviewMouseDown="locationScrollUpButton_PreviewMouseDown" BorderThickness="0" PreviewTouchDown="locationScrollUpButton_PreviewTouchDown" PreviewTouchUp="locationScrollUpButton_PreviewTouchUp" >
    <StackPanel>
        <TextBlock x:Name="locationUpButtonText" Text="Up" FontSize="13" Margin="0,2,0,4" HorizontalAlignment="Center" VerticalAlignment="Center"/>
        <Image x:Name="locationUpButtonImage" Source="/ProjectName;component/Resources/CaptureView/Location-Scroll-Up-White.png" Width="55" Height="60"/>
    </StackPanel>
</Button>

Upvotes: 8

Views: 8008

Answers (2)

Khalil Khalaf
Khalil Khalaf

Reputation: 9397

So I ended up doing it using a cool hack. Based on Ahmad's answer on this other question HERE we know the fire order of the handlers:

On Touch Devices:

TouchDown > PreviewMouseDown > TouchUp > PreviewMouseUp

On Non Touch:

PreviewMouseDown > PreviewMouseUp

And based on @M.Kazem comments here. The fix now looks something like this:

private bool ButtonPreview = true;
private void Button_TouchDown(object sender, TouchEventArgs e)
{
    // task 1
    ButtonPreview = false;
}
private void Button_TouchUp(object sender, TouchEventArgs e)
{
    // task 2
    // ..
}
private void Button_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    if (ButtonXPreview)
    {
        // task 1
    }
    else
        ButtonXPreview = true;

}
private void Button_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
    if (ButtonXPreview)
    {
        // task 2
    }
    else
        ButtonXPreview = true;
}

Upvotes: 4

Rob LaDuca
Rob LaDuca

Reputation: 191

Check the StylusDevice property of the MouseEventArgs. If it is null, then the mouse event is not a promoted touch event. If it's not null, then the StylusDevice will be the touch device that initiated the touch that got promoted.

Upvotes: 10

Related Questions