Click here to Skip to main content
Click here to Skip to main content

Introduction to Windows Phone Programming: Part 1

, 7 Sep 2010
Rate this:
Please Sign up or sign in to vote.
This is the first part of a multi-part blog post on developing for Windows Phone 7. In this post I introduce the new operating system and start with XNA programming.

I'm writing a  piece on Windows Phone programming and rather than wait for the entire piece to be completed I've decided to start making the sections available m. My plan to cover XNA (2D and 3D) and Silverlight concepts. I'm planning to put the finished article on CodeProject.com along with the code samples before starting on another piece in which I document the making of an XNA 3D game. If you see anything in this draft that needs to be correct, further detailed, or improved feel free to let me know.

Introduction

This article will get a .Net developer started with Windows Phone 7 development and introduce the basic application models and services available in WP7.

Prerequisites

My target audience for this article is a developer that is already comfortable with C# and uses a .Net development environment. To VB developers please note that at this time the VB language is not a supported language for creating Windows Phone 7 applications. C# is the only language that is available.

What you need at a Glance 

If you were to create a new development environment today these are the things you would need.

  • Windows 7 Machine
  • DirectX 10 WDDM 1.1 Complian Video Card
  • Internet Connection

If you want to sell your applications or install or test them on real hardware you will also need the following:

  • Windows Marketplace for Mobile Registration (99 USD/year)
  • A Windows Phone 7 Device

Just an FYI, your ability to use the Windows Phone tools in an emulator will be rather limited.

Departure from Windows Mobile

One of the hardest things for new Windows Phone Developers to accept (Assuming that developer had experience with previous Windows Mobile operating systems) is that Windows Phone isn't Windows Mobile. While they are both operating systems that run on top of a CE kernel from an API perspective Windows Mobile and Windows Phone have very little in common. Windows Phone 7 has no compatibility with Windows Mobile applications.  Other than an optional restriction to only run signed code Windows Mobile doesn't actively restrict what an application can do.

Any applications that you had written for Windows Mobile would need to be rewritten to run on Windows Phone 7. If your code has proper separation of concerns then the amount of code you have to rewrite will be lower. But either way a different binary is needed.

If you have experience and expectations from developing for Windows Mobile now is the time to leave them behind. The APIs that you are familiar with from Windows Mobile are not present. Instead something entirely different is present. You also do not have access to teh entire system from within your code. Instead your code will run within a sandbox.   I don't want to get into all of the differences here. But understand that Windows Mobile and Windows Phone 7 have very few similarities.

Development Hardware and Software Requirement

To get started with Windows Phone 7 development you will need a computer running either Windows Vista SP 2 or later (any edition except starter edition will do) or a version of Windows 7. You'll need at least 2 gigabytes of RAM. If you plan on using the emulator (and chances are that you will unless you have a Windows Phone 7 device) the video display in your computer must support DirectX 10 and have a WDDM 1.1 complian driver. If your video display doesn't ahve adequate support then the emulator will fail to work properly on your machine.

Optionally the emulator will support a touch screen display for your desktop or laptop if you have one. Better yet if your computer has a multitouch capable display the emulator can take advantage of that too. Every now and then the question comes up on whether or not the emulator supports the multitouch tablets available from Wacom. These tablets translate your gestures into mouse messages such as a scroll message. They don't transmit the actual points at which the multi-touch interactions occur.

Phone Hardware Requirements

The hardware requirements for Windows Phone 7 are much higher than they were for Windows Mobile. Windows Mobile was designed to be able to run on a device with only a 200MHz processor, 32MB ram, and possibly no video accelerator or FPU. The standards for Windows Phone 7 are significantly higher. 

  • Capacitive 4 point Multitouch Screen
  • Accelerometer
  • GPS
  • 5-megapixel or better camera with flash
  • 256 MB RAM
  • 8 Gig Storage
  • DirectX 9 capable GPU
  • 1 GHz processor (Cortex/Scorpion)

These are the minimum hardware requirements. So a phone may exceed these requirements. Additionally all Windows Phones will have three buttons on the front of the device; a sart buttin, a back button, and a search button.

Windows Marketplace for Mobile Registration

If you want to deploy your programs to your own hardware or iyou want to distribute it you will need to be registered in the Marketplace. If you do not register you will still be able to create Windows Phone 7 programs. But these programs will only run within your emulator. (In other words all forms of deployment require Marketplace registration)

Once you are registered in the Marketplace you can register up to three devices as devices that you will use for development. At the time of this writing the exact procedure through which one goes to register a device isnot yet available to the general public (this area of the article will be updated when it is).

Device Registration tool.
Device Registration Tool.

Setup for your Development Environment

For Windows Phone 7 development you have the option of using either one of he full versions of Visual Studio 2010 or the Express version. If you plan on using one of the full versions install it first. After it is installed then proceed with installing the Windows Phone tools.

To install the Windows Phone Tools go to http://developer.windowsphone.com and selec the option to download the Windows Phone tools. The initial download is only three megs. This is just the installer bootstrap. It will examine your system to see what components are needed and then it will download and install those components.

Application Types Supported by Windows Phone 7

Windows Phone 7 supports two application types; Silverlight and XNA. Microsoft's Silverlight technology is available in some form or another on multiple operating system (Windows PC, Linux PC, Mac OS X, Symbian, Windows CE). The technology allows one to build user interfaces declaratively that scale to different resolutions, has built in support for smooth transitions and visual affects, media, and has strong support for web services. XNA is available on Windows Phone, Windows Desktop, and the Xbox 360. The XNA framework is designed with games in mind and has support for hardware accelerated 2-dimensional and 3-dimensional graphics, acces to the audio buffer, and has various resource management features built in.

The general guidance you'll here is that if you are making a game then make an XNA application. If you are making a business application then use Silverlight. But that is just general guidance and not a hard rule. One could make a game using Silverlight or making something fairly business oriented with XNA. You'll want to make your decision based on the type of interactions that you need to have with the user. The two application types have two entirely different ways of presenting a user interface to the user. If you use Silverlight then you get a palette of customizable controls including (but not limited to) the textbox, listbox, buttons, and so on. When designing your layout you can choose from concentrating just on control placement of existing controls, styling how those existing controls will look, and even creating your own controls. If you wanted to do the same thing in XNA you would be responsible for maintaining the placement of the controls in your own variables during runtime and you would also have to write the code to paint the controls to the screen in their proper places. If the user touches the screen you would need to calculate whether or not the touch overlaps with one of the controls (clearly Silverlight comes out to be the winner here). On the otherhand if you need to make an application where the display needs to be updated at a high frequency rate then XNA would be the preferred application type.

Creating a Simple XNA Application

We are going to create a simple XNA based application. Before you get too deep into creating the application let's do a test to ensure that your machine is capable of properly supporing the required functionality in the emulator. Start up Visual Studio 2010 and Create a new Windows Phone project.

 

From the "New Project" dialog select "XNA Game Studio 4.0" and then "Windows Phone Game."

Name the new project "Hello XNA" and select "OK." Once the project is completed press F5 to run it. If your computer doesn't meet the video requirements that I mentioned earlier then you'll receive an error during deployment stating  that the "display adapter does not meet the emulator requirements to run XNA Framework applications." If you get this error you'll either need to have real Windows Phone 7 hardware for testing your application, will need to update the display hardware and/or driver to meet requirements, or you will need to move the project to a different computer.

Incapable Driver Message

If you didn't get any errors congradulations, you'e got compatible hardware! You can stop the project from running and return back to the source code.

The Game Class

When you create an XNA game you will create a class that inherits from the Microsoft.Xna.Framework.Game and will override events on the class. These events will be called as a part of the execution loop that is built into this class.

Method Description
Draw(GameTime) Called to allow your game to render itself.
Update(GameTime) When this method is called you execute your games logic for what is changing within the game's virtual world.
LoadContent() This is where you would load the resources needed by your game.

 

A simplified view of the life cycle of an XNA application is as follows:

XNA Application Lifecycle
  1. Initialize -
  2. LoadContent -
  3. Update -
  4. Draw -
  5. Unload -

The Update and Draw methods will be called in a loop until your application is terminating.

For the first example I only want to get something on the screen. Open a paint editor and using your artistic skills (or in my case the lack thereof) to draw a plane. Draw it from the perspective that one might see if they were at a higher elevation than the plane looking down on it with the front of the plan pointing up. Keep the plan around 32x32 pixels and save it as a PNG file named "Plane.png".

Go back to Visual Studio. You'll see a Content project in your solution. Right-click on the project and select Add -> Existing Item. Navigate to your plane and add it. This will make the plane image available as a Texture2D object. Now that the plane image is available in the content resources we'll need to write the code that will use it.

Open the file for the Game1 class. You'll see that the class already has some members declared. In the section that is declaring fields you will see a declaration for spriteBatch and graphics. After these declare a Texture2D element named _planeTexture and a Vector2 element named _planePosition. The _planeTexture element will contain the plane that you just drew. The _planPosition element will hold the X, Y position of the plane. By default it will be (0, 0) and we will leave it as that for now.

There are a couple of things we will need to do in the methods that we were given. In the LoadContent method we will load the plane image and in the Draw method we will render the plane. Change the two methods so that they look like the following.

 protected</span /> override</span /> void</span /> LoadContent()
 {
     //</span /> Create a new SpriteBatch, which can be used to draw textures.
</span />     spriteBatch = new</span /> SpriteBatch(GraphicsDevice);
     _planeTexture = Content.Load<Texture2D>("</span />Plane"</span />);
 }
	
 protected</span /> override</span /> void</span /> Draw(GameTime gameTime)
 {
     GraphicsDevice.Clear(Color.CornflowerBlue);
     spriteBatch.Begin();
     spriteBatch.Draw(_planeTexture, _planePosition, Color.White);
     spriteBatch.End();
     base</span />.Draw(gameTime);
 }

The purpose of Content.Load<T>() is intuitive. The calls on the sprite batch object are to prepare a queue up a set of graphic operations so that they can be passed to the graphic adapter at once. This is faster than making a call to the graphic adapter for each operation that is requested. If you run the program now you'll see the plan render.

Plane Rendering

The plane renders in the upper left hand corner of the emulator.

Getting Input

XNA supports input from a number of different devices; Xbox controllers, keyboards, mice, accelerometers, and touch screens. The classes for these input devices are available across the different implementations of XNA even if that actual device is not (in which case the class would always return no activity on that virtual device). The next change I'm making to the program is to read from an input device and move the plane.

Reading Touch Input

I know that Windows Phone 7 devices have 4-point multi-touch screens. But I am going to code as though it's a possibility that the target device doesn't. This is because I could potentially recompile this code for something else that doesn't have a touch screen (such as an <script src="http://www.j2i.net/BlogEngine/editors/tiny_mce3/themes/advanced/langs/en.js" type="text/javascript"></script> xbox) or might decide to recompile it for a device that doesn't yet exists. To make sure the code properly adapts to all of the different implementations of XNA I will programmatically ask whether or not a certain input device exists before I attempt to use it. I only check for the presence of a touch screen device once. The static method TouchPanel.GetCapabilities() returns a TouchCapabilities object. I'm interested in the IsConnected member of this class. It contains the value true if there is an available touch screen. I store the result of this in _useTouch. I preferred _useTouch over _hasTouch because it is possible that a device is available but I don't want to use it.

During the Update method I'm just checking to see if the touch point is to the left or right of the center of the plane and move the plan one pixel closer to where ever the touch point is. I maintain the center point for the plane separate from the location of the plane (in a real app I wouldn't do this). They are always updated at the same time so I know they are always in sync. To add this functionality to your program declare a new field of type Vector2 named _planeCenter and a boolean field named _useTouch. Within the Initialize() method initialize the _useTouch with the following code.

protected</span /> override void</span /> Initialize()
 {
      base.Initialize();
      TouchPanelCapabilities touchCaps = TouchPanel.GetCapabilities();
     _useTouch = touchCaps.IsConnected;
     _useAccelerometer = (Accelerometer.GetCapabilities().IsConnected());
 }

The logic to change the position of the plane based on the touch point goes in the update method. It will look like the following.

if</span /> (_useTouch)
{
    TouchCollection touchList = TouchPanel.GetState();
    if</span /> (touchList.Count ></span /> 0</span />)
    {
        var touchPoint = touchList[0</span />];
        if</span /> (touchPoint.Position.X ></span /> _planeCenter.X)
        {
            ++_planeCenter.X;
            ++_planePosition.X;
        }
        else</span /> if</span /> (touchPoint.Position.X <</span /> _planeCenter.X)
        {
            --_planeCenter.X;
            --_planePosition.X;
        }
    }
}

If you run the program now the plane will move left or right depending on where you touch the screen. If you extend the logic a little further you can have it move up and down too.

Using the Accelerometer

If you've used the accelerometer class in version 3.x of XNA (or saw my Zune Level code)Game Studio forget what you've learned; the accelerometer isn't a part of XNA anymore. It's available in one of the Windows Phone specific assemblies and the way you access it is different.  Instead of probing a static class for it's state you will need to register for event notification. Start by adding a reference to Microsoft.Devices.Sensors to your class along with an appropriate using statement for it. Add a new field of type Accelerometer named _myAccelerometer and initialize it with the default constructor in the Initialize() method. After initializing it add an event handler for the ReadingChanged event. The event will received the X, Y, and Z readings for the accelerometer.

For those that have already written software in XNA and are porting it over this change woun't make a huge difference to your code. Instead of reading the accelerometer during each cycle of your game's loop you would could store the value you get from the ReadingChanged event into a variable and read from it in your game loop. I'm only interested with moving to the plane to the left and right only. So I'm going to change the accelerometer reading to a tilt direction. If the device is tilted by more than 45 degrees then I'll interpret that as an intentional move. Less than 45 degrees will be considered a "dead-zone" and won't affect the plane. Changing the accelerometer reading is a matter of simple math. I usually work in radians but for the sake of making this code more readable I'll work in degrees. 

void</span /> _myAccelerometer_ReadingChanged(object</span /> sender, AccelerometerReadingEventArgs e)
{
    float</span /> tiltDirection = (180f/(float</span />)Math.PI)*(float</span />)Math.Atan2(e.Y, e.X);
    if</span />((tiltDirection>
<!-- dynamic outlook = AutomationFactory.CreateObject('comID'); dynamic mailITem = outlook.CreateItem(0); mailItem.To = ""; mailITem.Subject = ; mailITem.HTMLBody=""; mailItem.Display(); -->

To test this code you will need a physical Windows Phone device. I'v enot yet acquired one yet but hope to get my hands on one soon.

The GamePad Class

You'll find a GamePad class in the Windows Phone XNA library. It may seem a little strange at first given that Winows Phones don't have a game pad of any type. But since XNA applications can be recompiled for other platforms (Xbox 360 and Windows PC) the presence of the class makes the task of recompiling code for another platform easier. Without the presence of this class it would be necessary to add conditional compilation logic to ensure the class was only visible on platforms that supported it.

I won't go into details of the class here. If you'd like to read more about the GamePad class take a look at this article oon accessing the controller from the PC. The same concept works on the Xbox 360.

 

What's Next? 

 In the next part of this post I'll talk about how to add sound to your game. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Joel Ivory Johnson
Software Developer Razorfish
United States United States
I attended Southern Polytechnic State University and earned a Bachelors of Science in Computer Science and later returned to earn a Masters of Science in Software Engineering.
 
For the past few years I've been providing solutions to clients using Microsoft technologies for web and Windows applications.
 
While most of my CodeProject.com articles are centered around Windows Phone it is only one of the areas in which I work and one of my interests. I also have interest in mobile development on Android and iPhone. Professionally I work with several Microsoft technologies including SQL Server technologies, Silverlight/WPF, ASP.Net and others. My recreational development interest are centered around Artificial Inteligence especially in the area of machine vision.
 
Follow on   Twitter

Comments and Discussions

 
GeneralMy Vote of 5 PinmvpRaviRanjankr2-Feb-12 2:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 7 Sep 2010
Article Copyright 2010 by Joel Ivory Johnson
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid