共用方式為


Platform detection I: How to detect that your app is running in the emulator

When you develop your Windows CE or Windows Mobile application in .NET Compact Framework, you probably do a lot of testing on the Microsoft Device Emulators for Smartphone and Pocket PC.  Here I describe how to detect whether your program is running on an emulator or a physical device.

Microsoft's Device Emulator gives itself away through a WinCE API called SystemParametersInfo when you pass in the argument SPI_GETOEMINFO.  We'll use this to check for the emulator.  When we detect something other than the Microsoft value, we must be running on a physical device. 

I use partial classes because in later posts in the Platform Detection series I'll add more to these classes.

 using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Text;

namespace PlatformDetection
{
    internal partial class PInvoke
    {
        [DllImport("Coredll.dll", EntryPoint = "SystemParametersInfoW", CharSet = CharSet.Unicode)]
        static extern int SystemParametersInfo4Strings(uint uiAction, uint uiParam, StringBuilder pvParam, uint fWinIni);

        public enum SystemParametersInfoActions : uint
        {
            SPI_GETPLATFORMTYPE = 257, // this is used elsewhere for Smartphone/PocketPC detection
            SPI_GETOEMINFO = 258,
        }

        public static string GetOemInfo()
        {
            StringBuilder oemInfo = new StringBuilder(50);
            if (SystemParametersInfo4Strings((uint)SystemParametersInfoActions.SPI_GETOEMINFO,
                (uint)oemInfo.Capacity, oemInfo, 0) == 0)
                throw new Exception("Error getting OEM info.");
            return oemInfo.ToString();
        }

    }
    internal partial class PlatformDetection
    {
        private const string MicrosoftEmulatorOemValue = "Microsoft DeviceEmulator";
        public static bool IsEmulator()
        {
            return PInvoke.GetOemInfo() == MicrosoftEmulatorOemValue;
        }
    }
    class EmulatorProgram
    {
        static void Main(string[] args)
        {
            MessageBox.Show("Emulator: " + (PlatformDetection.IsEmulator() ? "Yes" : "No"));
        }
    }
}

This is the first post in a series of three on platform detection.  Coming up next: discerning between Smartphones and Pocket PCs.

Comments