Search code examples
c#wpftouchmouseeventtouch-event

Why my Mouse Event Handlers are not working when I have Touch Event Handlers?


Some of my end users have touch screens, and others have PCs. On touch screens, PreviewMouseUp/Down fire along with the touch event handlers, causing duplicate behavior (functions written in PreviewMousUp/Down get executed twice).

So my sample Button XAML:

<Button x:Name="Whatever" Background="Transparent"  MouseUp="Whatever_MouseUp" MouseDown="Whatever_MouseDown" TouchUp="Whatever_TouchUp" TouchDown="Whatever_TouchDown">
    <StackPanel>
        <TextBlock x:Name="WhateverText" Text="Soemthing" FontSize="13"/>
        <Image x:Name="WhateverImage" Source="bla/bla/bla"/>
    </StackPanel>
</Button>

Why MouseDown and MouseUp event handlers are not getting fired on the PC?

If I execute on a touch screen, it works like a charm (Touch event handlers). However, on my PC(VS-2015) it doesn't work at all. Please and thanks


Solution

  • It seems that the Click event handler prevents firing events of MouseDown and MouseUp. I expect that because when I build custom controls like buttons from scratch, I use these events to fire Click event. This is my expectation only.

    Anyway, I tried it and PreviewMouseDown/Up is fired on both touch and non-touch if you didn't implemented TouchDown/Up. But if you implemented TouchDown/Up with them, execution on TOUCH will be like this: > TouchDown > PreviewMouseDown > TouchUp > PreviewMouseUp. And execution on NON-TOUCH will be like this: > PreviewMouseDown > PreviewMouseUp. So I suggest on you to use PreviewMouseDown/Up because it works for both touch and non-touch.

    Also you can use MouseRightButtonDown/Up it will work with you. But you will note that MouseDown/Up is fired after it. You can simply prevent that by adding e.Handled = true; inside MouseRightButtonDown/Up handlers.

    Try to make use of these hints and if you couldn't solve it just tell me and I'll think with you. Good luck.