====== 017 加速度センサーの利用 ====== {{:wiki:windowsphone:7.1:tips:w_phone_017_001.png?100 |}} {{:wiki:windowsphone:7.1:tips:w_phone_017_002.png?100 |}} ===== 概要 ===== 加速度センサーの値を取得し、画面に表示します。WindowsPhoneではエミュレータでも加速度センサーの計測が可能です。 ==== FrameWorkの追加 ==== * メニューの [Project]から、[Add Reference] から、"Microsoft.Devices.Sensors" の参照を追加します。 * サンプルではVector3型を使用しているため、Microsoft.Xna.Frameworkも追加しています。 ==== MainPage.xaml ==== >]]> ==== MainPage.xaml.cs ==== using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Shapes; // 参照に。Microsoft.Devices.Sensorsを追加する。 using Microsoft.Devices.Sensors; using Microsoft.Phone.Controls; using Microsoft.Xna.Framework; namespace BaseApp { // エントリーポイント public partial class MainPage : PhoneApplicationPage { private Accelerometer accelerometer; private Vector3 accelReading = new Vector3(); private TextBlock textBlockX = null; private TextBlock textBlockY = null; private TextBlock textBlockZ = null; // コンストラクタ public MainPage() { // コンポーネントの初期化。 InitializeComponent(); // 初期化完了後に呼ばれるメソッドの登録。 Loaded += OnLoaded; } // 初期化完了後に呼ばれるメソッド。 void OnLoaded(object sender, RoutedEventArgs args) { // 加速度センサーのオブジェクトを生成。 accelerometer = new Accelerometer(); //イベント処理の登録 accelerometer.CurrentValueChanged += new EventHandler>(OnCurrentValueChanged); // 計測開始。 accelerometer.Start(); // 計測結果表示用のテキストテキストブロック。 { SolidColorBrush brush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 255, 255, 255)); textBlockX = new TextBlock(); textBlockX.FontFamily = new FontFamily("MS ゴシック"); textBlockX.FontSize = 32; textBlockX.Foreground = brush; textBlockX.Text = "X:"; Canvas.SetLeft(textBlockX, 10); Canvas.SetTop(textBlockX, 10); LayoutRoot.Children.Add(textBlockX); textBlockY = new TextBlock(); textBlockY.FontFamily = new FontFamily("MS ゴシック"); textBlockY.FontSize = 32; textBlockY.Foreground = brush; textBlockY.Text = "Y:"; Canvas.SetLeft(textBlockY, 10); Canvas.SetTop(textBlockY, 50); LayoutRoot.Children.Add(textBlockY); textBlockZ = new TextBlock(); textBlockZ.FontFamily = new FontFamily("MS ゴシック"); textBlockZ.FontSize = 32; textBlockZ.Foreground = brush; textBlockZ.Text = "X:"; Canvas.SetLeft(textBlockZ, 10); Canvas.SetTop(textBlockZ, 90); LayoutRoot.Children.Add(textBlockZ); } } // 計測イベント受け取り用メソッド。 private void OnCurrentValueChanged(object sender, SensorReadingEventArgs e) { // 非同期呼び出し。 Dispatcher.BeginInvoke(() => ReadinValueChanged( e.SensorReading ) ); } // 加速度センサーのパラメータを取得。 private void ReadinValueChanged(AccelerometerReading reading) { accelReading = reading.Acceleration; textBlockX.Text = "X:" + accelReading.X; textBlockY.Text = "Y:" + accelReading.Y; textBlockZ.Text = "Z:" + accelReading.Z; } } }