|
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.Shapes;
using Microsoft.Phone.Controls;
//引用
//Accelerometer类用到
using Microsoft.Devices.Sensors;
//Dispatcher类用到
using System.Windows.Threading;
namespace GetAccelerometerCoordinates
{
public partial class MainPage : PhoneApplicationPage
{
// 构造函数
public MainPage()
{
InitializeComponent();
//实例化加速计--知识点①
Accelerometer acc = new Accelerometer();
//加速计值发生变化是发生--知识点②
acc.ReadingChanged += new EventHandler<AccelerometerReadingEventArgs>(acc_ReadingChanged);
try
{
//开始获取加速计数据
acc.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//当加速计值改变时发生--知识点③
void acc_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
{
string str = "x:" + e.X + ";\nY:" + e.Y + ";\nZ:" + e.Z + ";\n矢量大小:" + Math.Sqrt(e.Z * e.Z + e.Y * e.Y + e.X * e.X) + ";\n时间戳:" + e.Timestamp;
//确定嗲用线程是否可以访问此对象--知识点④
if (txtCoordinates.CheckAccess())
{
txtCoordinates.Text = str;
}
else
{
//线程中异步实现txtCoordinates赋值--知识点⑤
txtCoordinates.Dispatcher.BeginInvoke(new SetTextDel(SetText), txtCoordinates, str);
}
}
//委托
delegate void SetTextDel(TextBlock txtCoordinates, string str);
//方法
void SetText(TextBlock txtCoordinates, string str)
{
txtCoordinates.Text = str;
}
}
} |
|
|