How To Get Tap Events Equivalent That Are Equivalent To Mouse Events

<< Back to the Windows Phone page

There are various methods for managing touch events. Perhaps the simplest (but least powerful) emulates a mouse by processing single-touch tap events equivalent to mouse-clicks. The tutorial below expands on the example found at http://create.msdn.com/en-US/education/quickstarts/Touch_Input

1. Tutorial Overview of Touch Input
For a brief overview of the different types of touch input, read the beginning of the tutorial at:
http://create.msdn.com/en-US/education/quickstarts/Touch_Input

2.Examine and try the program below on your phone (not the emulator)
TapDemo (zip) displays a rectangle that changes color and resizes depending on the tap events it receives, and shows the events invoked in a list box. Note that a tap down generates a sequence of 2 events: MouseEnter and MouseDown, while lifting off generates MouseUp and MouseLeave. This examples expands on the one found in the tutorial above.

a) Use XAML to build the interface and register your callbacks ; e.g., by putting the following into the Grid of the ContentPane

<StackPanel>
     <Rectangle Name="TestRectangle"
         Height="100" Width="200" Fill="Blue"
         MouseLeftButtonDown="Tap_LeftButtonDown"
         MouseLeftButtonUp="Tap_LeftButtonUp"
         MouseLeave="Tap_MouseLeave"
         MouseMove="Tap_MouseMove"
         MouseEnter="Tap_MouseEnter"
     />
     <ListBox x:Name="listBox1" Height="500"/>
</StackPanel>

b) Handle touch events in the callback methods by placing this after the constructor

int count = 0; // Used to track and display how many move events were invoked

private void Tap_MouseEnter(object sender, MouseEventArgs e)
{
    Feedback(sender, "Tap Enter", 50, 100, Colors.White);
}

private void Tap_LeftButtonDown(object sender, MouseButtonEventArgs e)
{
    Feedback(sender, "Tap Down", 300, 100, Colors.Red);
}


private void Tap_MouseMove(object sender, MouseEventArgs e)
{
    Feedback(sender, (count++).ToString() + " Move", 400, 100, Colors.Orange);
}

private void Tap_LeftButtonUp(object sender, MouseButtonEventArgs e)
{
    Feedback(sender, "Tap Up", 200, 100, Colors.Yellow);
}

private void Tap_MouseLeave(object sender, MouseEventArgs e)
{
    Feedback(sender, "Tap Leave", 200, 100, Colors.Blue);
    count = 0;
}

// Resize and recolor the rectangle, and add the message to the listbox
private void Feedback(object sender, string msg, double width, double height, Color color)
{
    Rectangle rect = sender as Rectangle;
    if (null != rect)
    {
        rect.Width = width;
        rect.Height = height;
        rect.Fill = new SolidColorBrush(color);
        this.listBox1.Items.Insert(0, msg);
     }
}