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

Managed DirectX Tutorial Part 1 - The Title Screen

By , 16 Jan 2003
 

Sample Image - mdxtutorial1.jpg

Introduction

Welcome to my first 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 offers 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 1, we will start with basic DirectDraw implementation by showing the title screen and text in full screen.

Requirements

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

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)
  • SNES Emulator with Super Metroid ROM (optional)

The Title Screen

Adding DirectX namespaces to the project

Add the references to Microsoft.DirectX.dll and Microsoft.DirectX.DirectDraw.dll to your project and add these namespaces to the project.

using Microsoft.DirectX;
using Microsoft.DirectX.DirectDraw;

Adding DirectX variables

First of all, we need to create a DirectDraw device. After that, we create the Surfaces. A Surface is a part of memory where you draw the needed stuff; it also acts like a layer. The Clipper is the boundaries you set to the device, so the device will not draw over the Clipper. The back Surface represents the BackBuffer. The title and text represents the layers of the title screen. Finally, the titlescreen string point to the bitmap to load into title Surface.

// The DirectDraw Device, used in all the application
private Device display;
// The Front Surface
private Surface front = null;
// The Back Surface
private Surface back = null;
// Surface to store the title screen
private Surface title = null;
// Surface to store the text
private Surface text = null;
// The Clipper
private Clipper clip = null;
string titlescreen = Application.StartupPath + "\\title.bmp";

Initialize DirectDraw

For initializing any Managed DirectX component, I suggest you to create methods for each component you use. Here is the method I used to init my DirectDraw stuff.

private void InitDirectDraw()
{
    // Used to describe a Surface
    SurfaceDescription description = new SurfaceDescription();
    // Init the Device
    display = new Device();
#if DEBUG
    display.SetCooperativeLevel(this, CooperativeLevelFlags.Normal);
#else
    // Set the Cooperative Level and parent, 
    //Setted to Full Screen Exclusive to the form)
    display.SetCooperativeLevel(this, 
        CooperativeLevelFlags.FullscreenExclusive);
    // Set the resolution and color depth 
    //used in full screen(640x480, 16 bit color)
    display.SetDisplayMode(640, 480, 16, 0, false);
#endif

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

#if DEBUG
    front = new Surface(description, display);
#else
    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);
#endif
    description.Clear();
#if DEBUG
    description.Width = front.SurfaceDescription.Width;
    description.Height = front.SurfaceDescription.Height;
    description.SurfaceCaps.OffScreenPlain = true;
    back = new Surface(description, display);
#else
    // 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);
#endif

    // Create the Clipper
    clip = new Clipper(display);
    /// Set the region to this form
    clip.Window = this;
    // Set the clipper for the front Surface
    front.Clipper = clip;

    // Reset the description
    description.Clear();
    // Create the title screen
    title = new Surface(titlescreen, description, display);

    description.Clear();
    // Set the height and width of the text.
    description.Width = 600;
    description.Height = 16;
    // OffScreenPlain means that this Surface 
    //is not a front, back, alpha Surface.
    description.SurfaceCaps.OffScreenPlain = true;

    // Create the text Surface
    text = new Surface(description, display);
    // Set the backgroup color
    text.ColorFill(Color.Black);
    // Set the fore color of the text
    text.ForeColor = Color.White;
    // Draw the Text to the Surface to coords (0,0)
    text.DrawText(0, 0, 
        "Managned DirectX Tutorial 1 - Press Enter or Escape to exit", 
        true);
}

The Draw method

The Draw is called each time we need to draw the content of the Surface to the screen.

private void Draw()
{
    // If the front isn't create, ignore this function
    if (front == null)
    {
        return;
    }

    // If the form is minimized, ignore this function
    if(this.WindowState == FormWindowState.Minimized)
    {
        return;
    }
    try
    {
        // Draw the title to the back buffer using source copy blit
        back.DrawFast(0, 0, title, DrawFastFlags.Wait);

        // Draw the text also to the back buffer using source copy blit
        back.DrawFast(10, 10, text, DrawFastFlags.Wait);

#if DEBUG
        // Draw all this to the front
        front.Draw(back, DrawFlags.Wait);
#else
        // Doing a flip to transfer back buffer to the front, faster
        front.Flip(back, FlipFlags.Wait);
#endif
    }

    catch(WasStillDrawingException)
    {
        return;
    }
    catch(SurfaceLostException)
    {
        // If we lost the surfaces, restore the surfaces
        RestoreSurfaces();
    }
}

The RestoreSurfaces method

The RestoreSurfaces method is called when the user defocus the application and then refocus the application (like an Alt-Tab switch).

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

    // Restore al the surface associed with the device
    display.RestoreAllSurfaces();
    // Redraw the text
    text.ColorFill(Color.Black);
    text.DrawText(0, 0, 
        "Managned DirectX Tutorial 1 - Press Enter or Escape to exit", 
        true);

    // For the title screen, we need to 
    //dispose it first and then re-create it
    title.Dispose();
    title = null;
    title = new Surface(titlescreen,  description, display);
    return;
}

The Final touch

At last, add the method InitDirectDraw to the constructor. Also implement the main loop of the application where the Draw method is used. Application.DoEvents() makes the application, process the messages event if the application is in a loop.

public Tutorial1()
{
    //
    // Required for Windows Form Designer support
    //
    InitializeComponent();
    // Initialize DirectDraw stuffs
    InitDirectDraw();
    // Remove the cursor
    this.Cursor.Dispose();
    // Show the form if isn't already do
    this.Show();
    // The main loop
    while(Created)
    {
        Draw();
        // Make sure that the application 
        //process the messages
        Application.DoEvents();
    }
}

Made a change to the Main method. Application.Run method doesn't work in this context. You need to create the form by yourself.

static void Main() 
{
    Tutorial1 app = new Tutorial1();
    Application.Exit();
}

The KeyUp event, is used to quit the Tutorial.

private void Tutorial1_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)
        this.Close();
}

Conclusion

In this tutorial, we learned how to show a bitmap in full screen using DirectDraw with Managed DirectX. The next tutorial will be on sprite animation and background music with AudioVideoPlayback. If you have any comments, suggestions, code corrections, please make me a remark in the bottom of the article.

History

Update 1.1

  • Fixed drawing on slower machines
  • Separated code for Debug and Release, suggestion by kalme
  • Release version more faster, doing a flip instead of a drawing

Update 1.0

  • First Release of Part 1

License

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

Shock The Dark Mage
Canada Canada
Member
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 (http://sf.net/projects/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 http://www.pixel-coders.tk

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1memberJacob Weber13 Oct '09 - 19:23 
GeneralDirectDraw is deprecatedmemberTimwiTerby27 Aug '09 - 22:16 
GeneralRemove the green screen from the imagemembervarunchetu22 Jul '09 - 2:09 
Questioncapturing moving objects in a videomembersbs11 Feb '09 - 8:32 
Questionhow to create a cube in c#.net using directx or openglmemberrajesh kumar swain16 Sep '08 - 0:27 
GeneralCould not setup graph. Value does not fall within the expectedmemberManjula M Kamadolli1 Jul '08 - 0:02 
GeneralRe: Could not setup graph. Value does not fall within the expectedmemberanatolibarski16 Jul '08 - 7:10 
QuestionHow to set transparent in the bitmap image?membermoonxp21 Oct '06 - 22:04 
GeneralApplying Alpha surfacememberFarooq Azam21 Dec '05 - 4:02 
GeneralSimilar problems no solutionmemberS020035629 Oct '05 - 12:10 
GeneralRe: Similar problems no solutionmembere2mars200614 Apr '06 - 18:26 
GeneralRe: Similar problems no solutionmemberz54528444717 Apr '09 - 6:43 
GeneralCode commentingmemberemmamiddlebrook18 Oct '05 - 11:29 
GeneralRe: Code commentingmemberArbitrary Programmer27 Jan '06 - 11:19 
GeneralRe: Code commentingmemberDaniel Carvalho Liedke2 Jun '06 - 2:50 
GeneralRe: Code commentingmemberKetil Wright1 Oct '07 - 9:40 
AnswerRe: Code commentingmemberNinethSense10 May '07 - 19:10 
GeneralI could not get the reference to Microsoft.directx.dll and Micrososft.Directx.DirectDraw.dllmemberjathesan13 Oct '05 - 23:24 
QuestionMicrosoft.directx.dll where from I should get???memberabcssssssa8 Aug '05 - 2:56 
AnswerRe: Microsoft.directx.dll where from I should get???sussAnonymous12 Aug '05 - 22:54 
GeneralRe: Microsoft.directx.dll where from I should get???sussAnonymous29 Aug '05 - 20:08 
AnswerRe: Microsoft.directx.dll where from I should get???memberSojaner30 Jun '06 - 15:18 
GeneralRe: Microsoft.directx.dll where from I should get???memberAlexander Morou18 Mar '10 - 11:36 
Generali find directX namespaces in the article project &i can't find it in minesussAnonymous29 Jul '05 - 15:03 
GeneralRe: i find directX namespaces in the article project &i can't find it in minesussAnonymous12 Aug '05 - 22:56 
AnswerRe: i find directX namespaces in the article project &i can't find it in minememberSojaner30 Jun '06 - 15:24 
Generaltransparency problemssussMishan Pog30 Apr '05 - 10:47 
GeneralRe: transparency problemssussMartinRiggs28 Jun '05 - 12:50 
GeneralRe: transparency problemsmembermoonxp5 Nov '06 - 18:57 
GeneralDrawFast Doesn't worksussMishan Pog25 Apr '05 - 7:37 
Generalabout the main loop..memberBob Meglio20 Apr '05 - 3:33 
GeneralRe: about the main loop..memberJudah Himango21 Aug '05 - 14:10 
GeneralI can't run this codesussMishan pog1 Apr '05 - 6:34 
GeneralRe: I can't run this codemembervoglster10 Apr '05 - 4:31 
GeneralRe: I can't run this codesussMishan Pog10 Apr '05 - 23:18 
GeneralRe: I can't run this codesussThe Ultimate Koala11 Apr '05 - 23:45 
GeneralRe: I can't run this codesussMishan Pog14 Apr '05 - 5:30 
GeneralRe: I can't run this codememberTheUltimateKoala15 Apr '05 - 5:53 
GeneralRe: I can't run this codesussMishan Pog15 Apr '05 - 8:06 
GeneralRe: I can't run this codememberseriously9 Jul '06 - 4:54 
GeneralRe: I can't run this codemembervoglster12 Apr '05 - 3:14 
GeneralRe: I can't run this codemembervoglster12 Apr '05 - 3:15 
GeneralRe: I can't run this codesussMishan Pog14 Apr '05 - 5:32 
GeneralRe: I can't run this codemembervoglster14 Apr '05 - 14:26 
GeneralRe: I can't run this codesussMishan Pog15 Apr '05 - 0:27 
GeneralThanks for your helpsussMishan Pog3 May '05 - 5:37 
GeneralRe: I can't run this codememberErlend9 Nov '05 - 1:29 
GeneralRe: I can't run this codemembervasia_huykin29 Mar '06 - 6:34 
GeneralSystem.IO.FileNotFoundExceptionmemberAlienKing12 Feb '05 - 10:33 
Generalerror on render()membereligetiv3 Feb '05 - 9:30 

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 17 Jan 2003
Article Copyright 2003 by Shock The Dark Mage
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid