In some instances when developing your Windows Phone 7 app using Silverlight you may want to know if your code is running within the emulator or within a real device. For example in my previous post on shake detection on Windows Phone 7 I didn’t want to create an new AccelerometerWithShakeDetection object if it was running in the emulator since the hardware is not available in the emulator.
In .NET Compact Framework it was a little bit of a pain to get this information as you have to PInvoke and have to know the native calls to get this information as follows
[DllImport("coredll.dll")] private static extern int SystemParametersInfo(uint uiAction,
uint uiParam, string pvParam, uint fWiniIni); private const uint SPI_GETOEMINFO = 258; public static bool IsEumlator() { string szOEMInfo = " "; string strOEMInfo = ""; // Get OEM Info int ret = SystemParametersInfo(SPI_GETOEMINFO, szOEMInfo.Length, szOEMInfo, 0); if (ret != 0) { strOEMInfo = szOEMInfo.Substring(0, szOEMInfo.IndexOf('\0')); return strOEMInfo.Equals("Microsoft DeviceEmulator"); } else throw new Exception("Unable to determine"); }
Using Silverlight for Windows Phone 7, you can now use the System.Environment.DeviceType which simply returns Unknown, Emulator or Device.
if (System.Environment.DeviceType == DeviceType.Emulator) { MessageBox.Show("You are running on the emulator."); } else if (System.Environment.DeviceType == DeviceType.Unknown) { MessageBox.Show("You are running on an unknown device."); } else { MessageBox.Show("You are running on a device"); }
Again, no more PInvokes since it’s not supported and the code is a lot easier to write and maintain.
So far in my working with Windows Phone 7 and Silverlight I haven’t required PInvoke functionality so far. We’ll see what happens in the future as the SDK gets out of CTP and we get customer projects but so far so good!
Funny I read this post by Raymond Chen just a few days back,
"If you can detect the difference between an emulator and the real thing, then the emulator has failed"
http://blogs.msdn.com/b/oldnewthing/archive/2010/05/19/10013611.aspx
🙂