Start Programming in Windows Phone 7

This chapter is taken from book "Programming Windows Phone 7" by Charles Petzold published by Microsoft press. http://www.charlespetzold.com/phone/index.html

Windows Phone 7: Microsoft Windows Phone 7 not only represents a break with the Windows Mobile past but also differentiates itself from other smartphones currently in the market. Windows Phone 7 devices will be made by several manufacturers and available with a variety of cell providers. All programs for Windows Phone 7 are written in .NET managed code, for it supports two popular and modern programming platforms: Silverlight and XNA.

Silverlight-a spinoff of the client-based Windows Presentation Foundation (WPF)-has already given Web programmers unprecedented power to develop sophisticated user interfaces with a mix of traditional controls, high-quality text, vector graphics, media, animation, and data binding that run on multiple platforms and browsers. Windows Phone 7 extends Silverlight to mobile devices.

XNA-the three letters stand for something like "XNA is Not an Acronym"-is Microsoft's game platform supporting both 2D sprite-based and 3D graphics with a traditional game-loop architecture. Although XNA is mostly associated with writing games for the Xbox 360 console, developers can also use XNA to target the PC itself, as well as Microsoft's classy audio player, the Zune HD.
The Silverlight and XNA platforms for Windows Phone 7 share some libraries, and you can use some XNA libraries in a Silverlight program and vice versa. But you can't create a program that mixes visuals from both platforms. Maybe that will be possible in the future, but not now. Before you create a Visual Studio project, you must decide whether your million-dollar idea is a Silverlight program or an XNA program.

The Hardware Chassis


The front of the phone consists of a multi-touch display and three hardware buttons generally positioned in a row below the display. From left to right, these buttons are called Back, Start, and Search:

1.gif

  1. Back Programs can use this button for their own navigation needs, much like the Back button on a Web browser. From the home page of a program, the button causes the program to terminate.
     
  2. Start This button takes the user to the start screen of the phone; it is otherwise inaccessible to programs running on the phone.
     
  3. Search The operating system uses this button to initiate a search feature.
The initial releases of Windows Phone 7 devices have a display size of 480 X 800 pixels. In the future, screens of 320 X 480 pixels are also expected. There are no other screen options for Windows Phone 7, so obviously these two screen sizes play a very important role in phone development.

2.gif

I will generally refer to these two sizes as the "large" screen and the "small" screen. The greatest common denominator of the horizontal and vertical dimensions of both screens is 160, so you can visualize the two screens as multiples of 160-pixel squares:

I'm showing these screens in portrait mode because that's usually the way smartphones are designed. The screen of the original Zune is 240 * 320 pixels; the Zune HD is 272 * 480. of course, phones can be rotated to put the screen into landscape mode. Some programs might require the phone to be held in a certain orientation; others might be more adaptable.

Sensors and Services


A Windows Phone 7 device is required to contain several other hardware features- sometimes called sensors-and provide some software services, perhaps through the assistance of hardware. These are the ones that affect developers the most:
  • Wi-Fi, Camera, Accelerometer, Location, FM Radio, Push Notifications.
A First Silverlight Phone Program

In the New Project dialog box, on the left under Installed Templates, choose Visual C# and then Silverlight for Windows Phone. In the middle area, choose Windows Phone Application. Select a location for the project, and enter the project name: SilverlightHelloPhone.

With the project loaded in Visual Studio, take a look at the Solution Explorer for the project. You'll see two pairs of skeleton files: App.xaml and App.xaml.cs, and MainPage.xaml and MainPage.xaml.cs. The App.xaml and MainPage.xaml files are Extensible Application Markup Language (XAML) files, while App.xaml.cs and MainPage.xaml.cs are C# code files.

I want to give you a little tour of these four files. If you look at the App.xaml.cs file, you'll see a namespace definition that is the same as the project name and a class named App that derives from the Silverlight class Application. Here's an excerpt showing the general structure:

namespace
SilverlightHelloPhone
{
    public partial class App :
Application
    {
        public App()
        {
          .....
            InitializeComponent();
            ....
        }
         ....
    }
}

All Silverlight programs contain an App class that derives from Application; this class performs application-wide initialization, startup, and shutdown chores. You'll notice this class is defined as a partial class, meaning that the project should probably include another C# file that contains additional members of the App class. But where is it?

The project also contains an App.xaml file, which has an overall structure like this:

<
Application
    x:Class
="SilverlightHelloPhone.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"      
    xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell
="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">
    ......
 </Application>


MainPage is the second major class in every Silverlight program and is defined in the second pair of files, MainPage.xaml and MainPage.xaml.cs. In smaller Silverlight programs, it is in these two files that you'll be spending most of your time.
Aside from a long list of using directives, the MainPage.xaml.cs file is very simple:

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;
 
namespace
SilverlightHelloPhone
{
    public partial class MainPage :
PhoneApplicationPage
    {
       
// Constructor
        public MainPage()
        {
            InitializeComponent();
        }
    }
}


The other half of this MainPage class is defined in the MainPage.xaml file. Here's the nearly complete file, reformatted a bit to fit the printed page, and excluding a section that's commented out at the end, but still a rather frightening chunk of markup:

<phone:PhoneApplicationPage

    x:Class
="SilverlightHelloPhone.MainPage"
    xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell
="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d
="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal
}"
    Foreground="{StaticResource PhoneForegroundBrush
}"
    SupportedOrientations="Portrait" Orientation
="Portrait"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight
="768"
    shell:SystemTray.IsVisible="True"> 
    <!--LayoutRoot contains the root grid where all other page content is placed-->
    <Grid x:Name="LayoutRoot" Background
="Transparent">
        <Grid.RowDefinitions
>
            <RowDefinition Height
="Auto"/>
            <RowDefinition Height
="*"/>
        </Grid.RowDefinitions>
 
       
<!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin
="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="SILVERLIGHT HELLO PHONE" Style="{StaticResource PhoneTextNormalStyle
}"/>
            <TextBlock x:Name="PageTitle" Text="main page" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style
}"/>
        </StackPanel>
 
       
<!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin
="12,0,12,0">
            <TextBlock Text
="Hello, Windows Phone 7!"
                       HorizontalAlignment="Center"
                       VerticalAlignment
="Center" />
        </Grid>
    </Grid
>
</
phone:PhoneApplicationPage
>

You can now compile and run this program:

4.gif

Color Themes

From the Start screen of the phone or phone emulator, click or touch the right arrow at the upper right and navigate to the Settings page and then select Theme. A Windows Phone 7 theme consists of a Background and an Accent color. For the Background you can select either Dark (light text on a dark background, which you've been seeing) or Light (the opposite). Select the Light theme, run SilverlightHelloPhone again, and express some satisfaction that the theme colors are automatically applied:

3.gif

Points and Pixels Another property of the TextBlock that you can easily change is FontSize:
FontSize="36"

But what exactly does this mean?

All dimensions in Silverlight are in units of pixels, and the FontSize is no exception. When you specify 36, you get a font that from the top of its ascenders to the bottom of its descenders measures approximately 36 pixels.
But fonts are never this simple. The resultant TextBlock will actually have a height more like 48 pixels-about 33% higher than the FontSize would imply. This additional space (called leading) prevents successive lines of text from jamming against each other.

The XAP is a ZIP


If you navigate to the \bin\Debug directory of the Visual Studio project for SilverlightHelloPhone, you'll find a file named SilverlightHelloPhone.xap. This is commonly referred to as a XAP file, pronounced "zap." This is the file that is deployed to the phone or phone emulator.

An XNA Program for the Phone


Next up on the agenda is an XNA program that displays a little greeting in the center of the screen. While text is often prevalent in Silverlight applications, it is less common in graphical games. In games, text is usually relegated to describing how the game works or displaying the score, so the very concept of a "hello, world" program doesn't quite fit in with the whole XNA programming paradigm.

From the File menu of Visual Studio select New and Project. On the left of the dialog box, select Visual C# and XNA Game Studio 4.0. In the middle, select Windows Phone Game (4.0). Select a location and enter a project name of XnaHelloPhone.

Visual Studio creates two projects, one for the program and the other for the program's content. XNA programs usually contain lots of content, mostly bitmaps and 3D models, but fonts as well. To add a font to this program, right-click the Content project (labeled "XnaHelloPhoneContent (Content)" and from the pop-up menu choose Add and New Item. Choose Sprite Font, leave the filename as SpriteFont1.spritefont, and click Add.

The word "sprite" is common in game programming and usually refers to a small bitmap that can be moved very quickly, much like the sprites you might encounter in an enchanted forest. In XNA, even fonts are sprites.

You'll see SpriteFont1.spritefont show up in the file list of the Content directory, and you can edit an extensively commented XML file describing the font.

<XnaContent xmlns:Graphics=
"Microsoft.Xna.Framework.Content.Pipeline.Graphics">
  <Asset Type="Graphics:FontDescription">
    <FontName>Segoe UI Mono</FontName>
    <Size>14</Size>
    <Spacing>0</Spacing>
    <UseKerning>true</UseKerning>
    <Style>Regular</Style>
    <CharacterRegions>
      <
CharacterRegion
>
        <
Start>&#32;</Start
>
        <
End>&#126;</End
>
      </
CharacterRegion
>
    </
CharacterRegions
>
  </
Asset
>
</
XnaContent>


In its initial state, the XNAHelloPhone project contains two C# code files: Program.cs and Game1.cs. The first is very simple and turns out to be irrelevant for Windows Phone 7 games! A preprocessor directive enables the Program class only if a symbol of WINDOWS or XBOX is defined. When compiling Windows Phone programs, the symbol WINDOWS_PHONE is defined instead. For most small games, you'll be spending all your time in the Game1.cs file. The Game1 class derives from Game and in its pristine state it defines two fields: graphics and spriteBatch. To those two
fields I want to add three more:

using
System;
using
Microsoft.Xna.Framework;
using
Microsoft.Xna.Framework.Graphics;
using
Microsoft.Xna.Framework.Input;
namespace
XnaHelloPhone
{
    public class Game1 : Microsoft.Xna.Framework.
Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        string text = "Hello, Windows Phone 7!";
        SpriteFont segoe14;
        Vector2 textPosition; 
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
           
// Frame rate is 30 fps by default for Windows Phone.
            TargetElapsedTime = TimeSpan.FromTicks(333333);
        }
        protected override void Initialize()
        {
            base.Initialize();
        } 
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            segoe14 = this.Content.Load<SpriteFont>("Segoe14");
            Vector2 textSize = segoe14.MeasureString(text);
            Viewport viewport = this.GraphicsDevice.Viewport;
            textPosition = new Vector2((viewport.Width - textSize.X) / 2,
                                       (viewport.Height - textSize.Y) / 2);
        }

        protected override void UnloadContent()
        {
        }
        protected override void Update(GameTime gameTime)
        {
           
// Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit(); 
            base.Update(gameTime);
        }
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Navy);
            spriteBatch.Begin();
            spriteBatch.DrawString(segoe14, text, textPosition, Color.White);
            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}

You can now compile and run this program:

5.gif

Oh, that's interesting! By default, Silverlight programs come up in portrait mode, but XNA programs come up in landscape mode. Let's turn the phone or emulator sideways:

6.gif

Summary

In this article, I discuss about the basic of programming in Windows Phone 7.


Similar Articles