Paul Michaels
Paul Michaels

Reputation: 16695

Detect movement or shaking in a windows 8 device

In Windows 8 Metro - given that it is intended to be used on a tablet, is it possible to detect if the device has been shaken or moved?

This article doesn't seem to cover device movement.

If this is possible then are there any online tutorials or code snippets available?

Upvotes: 2

Views: 562

Answers (1)

N_A
N_A

Reputation: 19897

I think you're looking for the acceleromator. Example.

using Windows.UI.Core;
using Windows.Devices.Sensors;

namespace AccelerometerCS
{

    partial class BlankPage
    {
        // Sensor and dispatcher variables
        private Accelerometer _accelerometer;

        // This event handler writes the current accelerometer reading to 
        // the three acceleration text blocks on the app's main page.

        private void ReadingChanged(object sender, AccelerometerReadingChangedEventArgs e)
        {
            Dispatcher.InvokeAsync(CoreDispatcherPriority.Normal, (s, a) =>
            {
                AccelerometerReading reading = (a.Context as AccelerometerReadingChangedEventArgs).Reading;
                txtXAxis.Text = String.Format("{0,5:0.00}", reading.AccelerationX);
                txtYAxis.Text = String.Format("{0,5:0.00}", reading.AccelerationY);
                txtZAxis.Text = String.Format("{0,5:0.00}", reading.AccelerationZ);

            }, this, e);
        }

        public BlankPage()
        {
            InitializeComponent();
            _accelerometer = Accelerometer.GetDefault();

            if (_accelerometer != null)
            {
                // Establish the report interval
                uint minReportInterval = _accelerometer.MinimumReportInterval;
                uint reportInterval = minReportInterval > 16 ? minReportInterval : 16;
                _accelerometer.ReportInterval = reportInterval;

                // Assign an event handler for the reading-changed event
                _accelerometer.ReadingChanged += new TypedEventHandler<Accelerometer, AccelerometerReadingChangedEventArgs>(ReadingChanged);
            }

        }
    }
}

Upvotes: 3

Related Questions