Click here to Skip to main content
13,007,600 members (66,502 online)
Click here to Skip to main content
Add your own
alternative version


81 bookmarked
Posted 31 Jan 2003

Managed DirectX Tutorial Part 2 - Samus Running

, 31 Jan 2003
Rate this:
Please Sign up or sign in to vote.
Step-by-step tutorial on Managed DirectX, Part 2 - Sprite animation and Audio playback.

Sample Image - mdxtutorial2.jpg


Welcome to the second part of my tutorial on Managed DirectX, included with DirectX 9 SDK. Most C# developers were waiting for this release. Before Managed DirectX, C# developers were using DirectX via COM Interop of DirectX 7 or 8 VB component. The new Managed DirectX components offer best performance and easier programming over DirectX COM Interop. This tutorial is for newcomers in DirectX development, like me, or for people who were using COM Interop for DirectX development. In this tutorial, we will make a clone of Super Metroid game called Managed Metroid. We will try to use all the components of Managed DirectX (DirectDraw, DirectSound, DirectInput, Direct3D, DirectPlay and AudioVideoPlayback).

In part 2, we will continue with sprite animation and audio playback with AudioVideoPlayback namespace.


These articles require some knowledge of C#. Also a basic game development background would be useful.

In this article, I assume that you have read the first part of the tutorial found at[^].

Software requirements:

  • Microsoft Windows NT4 SP6, Windows 2000, Windows XP Pro (for compiling only)
  • Visual C# .NET or Visual Studio .NET
  • DirectX 9 SDK Full or only C# Part (available from Microsoft)
  • Image editing tool (optional but useful)

Music playback

With Managed DirectX, if you want a quick way to playback music in your application then you're served. The AudioVideoPlayback namespace is a wrapper of the DirectShow API found in C++. So, you can play any type of audio and video unless that you have the codec on your computer.

We implant Audio Playback in a code like this (It's just a sample one, this is not in the demo project) :

private void PlayAudio(string audiofile)
    // Create the audio class with specified audio file
    Audio audio = new Audio(audiofile)
    // Play Audio

Adding namespace

Here are the references you need to add to the project for this tutorial (in the code and in References folder in solution)

using System.IO;
using Microsoft.DirectX;
using Microsoft.DirectX.AudioVideoPlayback;
using Microsoft.DirectX.DirectDraw;

Adding DirectX variables

First of all, we declare the DirectDraw device. This time, we also add a constant that hold the number of frames, an array of Rectangle that holds each frame of the animation and finally we add the sprite height and width in int.

After that, we declare the Audio playback variables. First of all, the Audio class needed to play the music. The m_playlist variable is an array of strings holding the music listed in directory music.

The Timer is used to animate the sprite by incrementing the currentframe variable. Finally, the helptext string stores the help text drawn on the screen.

// Direct Draw variables
//DirectDraw Device used in all the application
private Device display;
//Front Surface
private Surface front = null;
//Back Buffer Surface
private Surface back = null;
//Surface that hold the Samus Sprites
private Surface samus = null;
//Constant of number of frames
private const int nFrames = 8;
//Array of Rectangle to hold the position of the frames
private Rectangle[] frames = new Rectangle[nFrames];
//Sprite Height
private int samus_height = 49;
//Sprite Height
private int samus_width = 35;
//Current frame displayed
private int currentframe = 0;
//Path to the samus sprite
private string samus_sprite = Application.StartupPath + "\\samussprite.bmp";

// Audio Playback variables
//Audio Playback class
private Audio music;
//String of the musicpath
private string musicpath = Application.StartupPath + "\\music\\";
//The playlist initialized later
private string[] m_playlist = null;
//The maxindex, store the upper bounds of the playlist
private int maxindex = 0;
//Current index of the music played
private int musicindex = 0;

// Misc variables
//Timer used to cadence the sprite animation
private System.Windows.Forms.Timer TimerSprite;
//Help Text
private string helptext = 
    "Managed DirectX Tutorial 2 - Press Enter or Escape to exit";

Initialize audio playback

Initializing audio playback is very simple. Create the Audio class with an initial music file, then add the OnMusicEnding event. Finally, just play the music.

private void InitAudioPlayback()
    // Create the Audio class with the first element of the playlist
    music = new Audio(m_playlist[0]);
    // Event to handle the ending of the music
    music.Ending += new EventHandler(this.OnMusicEnding);
    // Play the music

FillPlaylist method

The FillPlaylist method lists the directory music and fills the m_playlist variable.

private string[] FillPlaylist()
    // Get the number of song
    maxindex = Directory.GetFiles(musicpath).Length;
    // Create the playlist
    string[] playlist = new string[maxindex];
    // Fill the playlist
    playlist = Directory.GetFiles(musicpath);
    // Return
    return playlist;

OnMusicEnding event

This function opens the next song in the play list. Instead of creating a new instance of the Audio class, we use the method Open to play the next song.

private void OnMusicEnding(object sender, System.EventArgs e)
    // Check if the Audio class is created
    if(music != null)
        // Increment the music idnex
        // Stop the current song played
        // If this is the song, return to the first song
        if(musicindex >= maxindex - 1)
            musicindex = 0;

            // Open the next song
            // Reset the Ending event
            music.Ending -= new EventHandler(this.OnMusicEnding);
            music.Ending += new EventHandler(this.OnMusicEnding);
            // Play it
            // If they are any problems, exit the application

Sprite animation

My method to animate a sprite is very simple. Here is the image I will animate:

With Jasc Animation Shop and Paint Shop Pro, I pasted all the frames of the animation into a single image:

So how do I select each frame in my application? We pre-compute the area of each frame and we store it in an array of Rectangle.

Each Rectangle has the size of each frame of the animation shown below. The Point locates the top-left point of the current frame. Imagine this like a selection in your favorite image editing program.

for(int i=0; i< nFrames; i++)
    Point pt = new Point(samus_width * i, 0);
    frames[i] = new Rectangle(pt, new Size(samus_width, samus_height));

But now, how do I draw each frame in my Draw method? The Draw and DrawFast methods of DirectDrawDevice can specify a region of the surface to draw with a Rectangle.

// Draw the title to the back buffer using source copy blit
back.DrawFast(320, 240, samus, frames[currentframe], 

Finally, we add a Windows Timer to our application. The Timer is used to set the tick of the animation.

private void TimerSprite_Tick(object sender, System.EventArgs e)
    if(currentframe >= nFrames - 1)
        currentframe = 0;

DirectDraw initialization

Now too much code has changed here. We added the pre-compute of the animation frames.

private void InitDirectDraw()
    // Used to describe a Surface
    SurfaceDescription description = new SurfaceDescription();
    // Init the Device
    display = new Device();

    // Set the Cooperative Level and parent, 
    // Setted to Full Screen Exclusive to the form
    // Set the resolution and color depth used in full screen 
    //(640x480, 16 bit color)
    display.SetDisplayMode(640, 480, 16, 0, false);

    // Define the attributes for the front Surface
    description.SurfaceCaps.PrimarySurface = true;

    description.SurfaceCaps.Flip = true;
    description.SurfaceCaps.Complex = true;

    // Set the Back Buffer count
    description.BackBufferCount = 1;

    // Create the Surface with specifed description and device)
    front = new Surface(description, display);


    // A Caps is a set of attributes used by most of DirectX components
    SurfaceCaps caps = new SurfaceCaps();
    // Yes, we are using a back buffer
    caps.BackBuffer = true;

    // Associate the front buffer to back buffer with specified caps
    back = front.GetAttachedSurface(caps);

    samus = new Surface(samus_sprite, description, display);

    for(int i=0; i< nFrames; i++)
        Point pt = new Point(samus_width * i, 0);
        frames[i] = new Rectangle(pt, new Size(samus_width, samus_height));

    // Set the fore color of the text
    back.ForeColor = Color.White;

DrawNextFrame method

The Draw method has changed name. It's now DrawNextFrame. We added the draw of the current frame. The current song played is also written on the screen.

private void DrawNextFrame()
    // If the front isn't create, ignore this function
    if (front == null)

    // If the form is minimized, ignore this function
    if(this.WindowState == FormWindowState.Minimized)
        // Draw the title to the back buffer using source copy blit
        back.DrawFast(320, 240, samus, 
                frames[currentframe], DrawFastFlags.DoNotWait);

        // Draw the text also to the back buffer using source copy blit
        back.DrawText(10, 30, helptext, false);
        back.DrawText(10, 50, "Playing : "+m_playlist[musicindex], false);

        // Doing a flip to transfer back buffer to the front, faster
        front.Flip(back, FlipFlags.DoNotWait);
        // If we lost the surfaces, restore the surfaces

RestoreSurfaces method

No changes for this method

private void RestoreSurfaces()
    // Used to describe a Surface
    SurfaceDescription description = new SurfaceDescription();

    // Restore al the surface associed with the device

    // For the samus sprite, we need to dispose it first 
    // and then re-create it
    samus = null;
    samus = new Surface(samus_sprite,  description, display);


In the constructor, we add the fill of the play list and we add the start of the timer.

public Tutorial2()
    // Required for Windows Form Designer support

    m_playlist = FillPlaylist();
    // Remove the cursor
    // Show the form if isn't already do
    TimerSprite.Enabled = true;
    // The main loop
        // Make sure that the application process the messages

The Closing event

The Closing event disposes the DirectX components used in the application.

private void Tutorial2_Closing(object sender, 
                System.ComponentModel.CancelEventArgs e)
    if(display != null)
        display.SetCooperativeLevel(this, CooperativeLevelFlags.Normal);

    if(music != null)

The KeyUp event

The KeyUp event is the same as in Part 1 of this tutorial.

private void Tutorial2_KeyUp(object sender, 
                System.Windows.Forms.KeyEventArgs e)
    // If the user press Escape or Enter, the tutorial exits
    if(e.KeyCode == Keys.Escape || e.KeyCode == Keys.Enter)

Main method

You need to make the same change as the first part.

static void Main() 
    Tutorial2 app = new Tutorial2();


In this tutorial, we learned how to animate a sprite using DirectDraw and play background music with Managed DirectX. The next tutorial will be an enhancement of Part 2 with DirectInput. If you have any comments, suggestions, code corrections, please make me a remark at the bottom of the article.

Known issues

  • The demo will exit by itself because the music failed to load.
  • When the demo exits, an error message box appears with a .NET Broadcast Event.


Update 1.0

  • First release of Part 2


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

I'm currently in College(Cegep) in Computer Science.

I'm developping since 2 years starting with C and now i'm an active C# developper.

1998 - Got my PC

1999 - Make my first web page

2000 - Started ROM Translation

2001 - Learned programming with C, first program(Final Fantasy 1 Trainer)

2002 - Learned C#, got VS.NET, started my first big programming project(Aeru IRC)

2003 - Continue Aeru IRC, Learn Managed DirectX, go to CEGEP.

2004 - Dumped Windows as my main desktop(using Gentoo Linux), remake Contra on GBA in C, learn x86 and ARM7 assembler.
2005 - Gamefu (

My current knowlegde in computer language:
ARM7 assembler, C, C++, C#, PHP and Delphi.

My current active projects is a coding group called Pixel Coders found at

You may also be interested in...

Comments and Discussions

GeneralA question About "new Audio(filename)" Pin
yanganok10-Jul-06 21:23
memberyanganok10-Jul-06 21:23 
GeneralTrouble playing audio! Pin
RedEgg200616-Feb-06 5:18
memberRedEgg200616-Feb-06 5:18 
GeneralSame as GDI+ Pin
Anonymous27-Jun-05 12:50
sussAnonymous27-Jun-05 12:50 
GeneralDirectDraw Transparency problem Pin
Mishan Pog3-May-05 5:56
sussMishan Pog3-May-05 5:56 
Generalexcellent resource, just one thing Pin
fueltooss24-Jan-05 4:34
memberfueltooss24-Jan-05 4:34 
GeneralSmall (almost irrelevant) tip Pin
reinux14-Dec-04 23:04
memberreinux14-Dec-04 23:04 
GeneralGreat Tutorial, Couple of Questions Pin
exhaulted12-Jul-04 23:43
memberexhaulted12-Jul-04 23:43 
GeneralRe: Great Tutorial, Couple of Questions Pin
Shock The Dark Mage1-Aug-04 2:21
memberShock The Dark Mage1-Aug-04 2:21 
GeneralRe: Great Tutorial, Couple of Questions Pin
exhaulted1-Aug-04 22:31
memberexhaulted1-Aug-04 22:31 
GeneralMultimonitor Pin
clockhar6-May-04 11:54
memberclockhar6-May-04 11:54 
QuestionIs that really the way you do it? Pin
al-Anfal31-Mar-04 3:40
memberal-Anfal31-Mar-04 3:40 
General&quot;DirectX&quot; not contained in namespace &quot;Micorsoft&quot; Pin
GMachiavelli27-Feb-04 7:18
memberGMachiavelli27-Feb-04 7:18 
GeneralRe: &quot;DirectX&quot; not contained in namespace &quot;Micorsoft&quot; Pin
apferreira27-Feb-04 7:47
memberapferreira27-Feb-04 7:47 
GeneralRe: &quot;DirectX&quot; not contained in namespace &quot;Micorsoft&quot; Pin
GMachiavelli27-Feb-04 8:00
memberGMachiavelli27-Feb-04 8:00 
GeneralRe: &quot;DirectX&quot; not contained in namespace &quot;Micorsoft&quot; Pin
mhusleag21-Apr-04 20:50
membermhusleag21-Apr-04 20:50 
GeneralImpressive but.... Pin
sinister x5-Jan-04 5:15
membersinister x5-Jan-04 5:15 
GeneralRe: Impressive but.... Pin
digitalse7en13-Feb-04 8:29
memberdigitalse7en13-Feb-04 8:29 
GeneralSprite flipping - Samus running two ways Pin
Deciheximal18-Dec-03 6:36
memberDeciheximal18-Dec-03 6:36 
QuestionHow to deal with DirectX Exception Pin
malei20037-Dec-03 3:34
membermalei20037-Dec-03 3:34 
GeneralExporting Frames from movie with AudioVideoPlayBack Pin
NicoVB6-Dec-03 0:59
memberNicoVB6-Dec-03 0:59 
Generalchanging the Bg color Pin
supertonic5-Dec-03 3:47
membersupertonic5-Dec-03 3:47 
GeneralRe: changing the Bg color Pin
dyerkess9-Mar-04 8:17
memberdyerkess9-Mar-04 8:17 
Generaltried this Pin
Anonymous14-Oct-03 16:52
sussAnonymous14-Oct-03 16:52 
GeneralMIDI Question that Probably Doesn't Belong Here Pin
cantgetnosleep20-May-03 4:18
membercantgetnosleep20-May-03 4:18 
GeneralRe: MIDI Question that Probably Doesn't Belong Here Pin
froguz::20-Oct-04 13:21
sussfroguz::20-Oct-04 13:21 

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

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

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170628.1 | Last Updated 1 Feb 2003
Article Copyright 2003 by Shock The Dark Mage
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid