This weekend I tried out “Resetting a Form by Shaking the Phone” from Windows Phone Recipes. This book is good for those programmers/coders/WP-fanatics (Yeah! fanatics) who are either just beginning with WP7 or just trying out their hands in it for fun!
For detecting shakes, we are going to use Accelerometer sensor, whose data are exposed by the AccelerometerReadingEventArgs class, which returns 3 properties for the x-, y-, and z-axis that assume values between -2 and 2 (direction of the vector of force).
The basic Accelerometer class is contained in the namespace Microsoft.Device.Sensors assembly.
The code is pretty simple and straight forward. XAML is having a textbox, whose content gets reset whenever we shake the phone.
XAML code:
<!–TitlePanel contains the name of the application and page title–>
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="Movers and Shakers" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Shake it Baby!" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0" Grid.RowSpan="6">
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBox Name="tbShake" Text="TextBlock" />
<TextBlock Text="Type and shake" Grid.Row="4" VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</Grid>
Code Behind for MainPage is also easy to follow. In MainPage ctor, we are adding our custom method, which initiates accelerometer and subscribe for the event “ReadingChanged”.
One odd thing in above code: We didn’t stop the accelerometer (expect more battery consumption). Just call .Stop() to do so.
Screenshot of the running App:
More details about the accelerometer class: http://msdn.microsoft.com/en-us/library/microsoft.devices.sensors.accelerometer(v=vs.92).aspx
//represents the time of the first significant movement
DateTimeOffset movementMoment = new DateTimeOffset();
double firstShakeStep = 0; //represents the value of the first significant movement
// Constructor
public MainPage()
{
InitializeComponent();
initAccelerometer();
}
private void initAccelerometer()
{
Accelerometer accelerometer = new Accelerometer();
accelerometer.ReadingChanged += new
EventHandler<AccelerometerReadingEventArgs>(Accelerometer_ReadingChanged);
accelerometer.Start(); //this can be done in a button_click
}
void Accelerometer_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
{
//if the movement takes less than 500 milliseconds
if (e.Timestamp.Subtract(movementMoment).Duration().TotalMilliseconds <= 500)
{
if ((e.X <= -1 || e.X >= 1) && (firstShakeStep <= Math.Abs(e.X)))
firstShakeStep = e.X;
if (firstShakeStep != 0)
{
firstShakeStep = 0;
Deployment.Current.Dispatcher.BeginInvoke(() => ResettbText());
}
}
movementMoment = e.Timestamp;
}
private void ResettbText()
{
this.tbShake.Text = "";
}
Download code from GitHub
