Greg Dolley’s Weblog

A Blog about Graphics Programming, Game Programming, Tips and Tricks

Managed DirectX C# Graphics Tutorial 1: Getting Started

Posted by gregd1024 on February 26, 2008

I’m going to demonstrate the same principles as my last post (DirectX 9 C++ Graphics Tutorial 1), how to fill a form with a solid color – except this time it’ll be in .NET using C# and Managed DirectX (MDX 1.1). MDX 1.1 is meant to expose most of the functionality as native DirectX 9.

Requirements

Everything in this tutorial is based on Visual Studio 2008 Express.

You’ll also need the DirectX SDK. You can download it from Microsoft’s site with this link. Note that this is the June 2007 release. I purposely didn’t link to the latest (November 2007 at the time of this writing) because Microsoft has removed the Managed DirectX samples and documentation from that release. If you read my last post, then you know that Microsoft has moved MDX’s functionality into the XNA framework, but threw out all features which were not simultaneously supported by both Xbox and Windows.

Tutorial Source and Project Files

To get the finished result of what this tutorial teaches – project files, binaries, and source – use this link:

Download C# Sources and Binaries [~10k]

Step 1: Create and Setup Your Project

We’re going to start from absolute scratch – that means no wizards and no auto-generated code. So start out by creating an empty C# project. You can name it whatever you like and place it in any directory.

Now add the following references:

  • Microsoft.DirectX
  • Microsoft.DirectX.Direct3D
  • System
  • System.Drawing
  • System.Windows.Forms

Go into your project settings and change the output type from “Console Application” to “Windows Application.”

managed_directx_tutorial_1_project_settings

Add one source file called “main.cs” (actually, you can use a different name but I’m going to refer to this file as “main.cs” throughout the tutorial).

Step 2: Create the Form

Inside “main.cs” you’re going to add the following “using” statements:

using System;

using System.Windows.Forms;

using Microsoft.DirectX;

using Microsoft.DirectX.Direct3D;

To make the form, copy the following code snippet and paste it directly underneath the “using” statements:

namespace MDX_Tutorial1
{
   class MainClass:Form
   {
      MainClass()
      {
         this.Text = “Managed DirectX Tutorial 1″;
      }

 

      static void Main()
      {
         MainClass MainForm = new MainClass();
         Application.Run(MainForm);
      }
   }
}

Step 3: Create the Device Object

Just like the previous post’s C++ example, you’ll have to create a device object. Since we’ll be accessing this object in multiple functions, it must be a class member variable. Add the following declaration inside “MainClass”:

private Device m_device = null;

Also add a method called “InitGraphics()” – this is where we’ll create and initialize the device object. The initialization code is only a few lines:

void InitGraphics()
{
   PresentParameters present_params = new PresentParameters();
  

   present_params.Windowed = true;
   present_params.SwapEffect = SwapEffect.Discard;
  

   m_device = new Device(0, DeviceType.Hardware, this,

                         CreateFlags.SoftwareVertexProcessing, present_params);
}

First, we create the “PresentParameters” object. This object describes how DirectX should behave in our application. We want the application to be a window and we’ll let the device handle the back buffer (“Windowed” and “SwapEffect”). Next, we actually create the device. There are several overloads for the constructor of “Device” but the one we’re interested in takes five arguments as described below:

  • Parameter 1: “int adapter”
  • Parameter 2: “DeviceType deviceType”
  • Parameter 3: “Control renderWindow”
  • Parameter 4: “CreateFlags behaviorFlags”
  • Parameter 5: “params PresentParameters[] presentationParameters”

For the adapter we used “0″ since this designates the default. We chose hardware rendering as opposed to software emulation. Our main application class is also our render target form (hence the “this” keyword). We wanted software vertex processing instead of hardware calculated transforms. Lastly, we passed in our “present_params” object as the fifth parameter.

Now we must call “InitGraphics()” from somewhere. Add the following line in “Main()”:

static void Main()
{
   MainClass MainForm = new MainClass();
   MainForm.InitGraphics(); // <— ADD THIS LINE
   Application.Run(MainForm);
}

Step 4: Draw on the Form

In order to draw on the form we must override the “OnPaint()” function. In this function we use the “m_device” member to call “Clear()” and “Present()” like this:

protected override void OnPaint(PaintEventArgs e)
{
   m_device.Clear(ClearFlags.Target,
                  System.Drawing.Color.FromArgb(0, 0, 255).ToArgb(), 1.0f, 0);
   m_device.Present();
}

The “Clear()” function fills one or more buffers with a single value. The first parameter specifies which buffer, or series of buffers, to fill. It can be the rendering target buffer (Target), depth buffer (ZBuffer), or stencil buffer (Stencil). You can specify more than one by combining their values via a bitwise “OR” operation. The second parameter specifies what color to use in clearing the render target surface. In our case we chose blue. The third parameter specifies what value to use for clearing the depth buffer. Lastly, the fourth parameter specifies what value to use for clearing the stencil buffer.

The “Present()” function displays everything to the screen. It is equivalent to calling the C++ version with four NULL parameters.

Run the Program!

Our first managed DirectX program is done! Now compile and run the program. You should see output similar to this:

managed_directx_tutorial_1_output

Conclusion

While this program is rather boring, in the next tutorial we’ll cover how to draw a 2D triangle with different colored vertices.

-Greg Dolley

*Get new posts automatically! Grab the RSS feed here. Want email updates instead? Click here.

About these ads

35 Responses to “Managed DirectX C# Graphics Tutorial 1: Getting Started”

  1. M Vitarana said

    Thanks for the tutorial…

    Helped me a lot with getting started…

    thanks

  2. gregd1024 said

    Glad it helped. ;-)

    -Greg

  3. Jake Kartchner said

    Yeah, thanks for the tutorial: a very clear example for the absolute beginner. Fine work.

    -Jake

  4. gregd1024 said

    Thank you, Jake. :-)

    -Greg

  5. Karl Lew said

    Many thanks for this article. I did run into a problem with the LoaderLock error. Here’s the link to solve the problem:

    http://www.thezbuffer.com/articles/304.aspx

    8) Karl

  6. novice 3d programmer said

    hi, where do you put the things like Parameter 1: “int adapter”??? I can’t figure it out. please help! Thanks! novice

  7. Brendan said

    I think I hit enter in the emial thing, so if it publishes two responses, sorry. I have tried to find this site again, but I could not. sorry for not responding for awhile. For one thing, this.Text = “Managed DirectX Tutorial 1″; has issues with the words Managed, Tutorial, and 1. Another thing I cannot understand: How and where do you add references?
    * Microsoft.DirectX
    * Microsoft.DirectX.Direct3D
    * System
    * System.Drawing
    * System.Windows.Forms
    go where??
    present_params.SwapEffect = SwapEffect.Discard; it doesn’t like SwapEffect.
    PresentParameters present_params = new PresentParameters(); it has issues with PresentParameters, and params.
    m_device = new Device(0, DeviceType.Hardware, this, it has problems with device and devicetype.
    CreateFlags.SoftwareVertexProcessing, present_params); it has issues with CreatFlags.
    m_device.Clear(ClearFlags.Target, it has issues with ClearFlags again.

    I have no other way to tell you these problems, and I have no idea what they are. any help would be appreciated.

  8. Brendan said

    I think I just fixed all the problems….. I found out where to add references, and that fixed almost everything. Sorry for taking your time.

  9. Brendan said

    FINALLY, it works perfectly!! the problem was something to do with me starting with a windows application and not going from console to windows application. Hurray!

  10. Kevin said

    I got this working fine on my Vista 64 bit machine after forcing the project to compile x86 instead of x64.
    I was getting a bad image format exception unhandled error. Something to do with the DirectX libs not 64-bit.

  11. Nathan said

    @Kevin – Thanks, I had gone through a couple of different tutorials and they all gave me the image format exception. Changing compilation to x86 fixed it!

  12. kaush said

    thanx i have started in c#

  13. meh said

    doesn’t run in visual C# 2008 express edition.

  14. David said

    First of all, i want to say that it’s a very good tutorial! I find it very easy to understand. Although, i got a few errors:

    Error 1 Unexpected character '“' C:\Documents and Settings\Ägaren\Lokala inställningar\Application Data\Temporary Projects\Training\main.cs 14 26 Training
    Error 2 Unexpected character '″' C:\Documents and Settings\Ägaren\Lokala inställningar\Application Data\Temporary Projects\Training\main.cs 14 53 Training
    Error 3 } expected C:\Documents and Settings\Ägaren\Lokala inställningar\Application Data\Temporary Projects\Training\main.cs 14 55 Training
    Error 4 Expected class, delegate, enum, interface, or struct C:\Documents and Settings\Ägaren\Lokala inställningar\Application Data\Temporary Projects\Training\main.cs 34 18 Training
    Error 5 Expected class, delegate, enum, interface, or struct C:\Documents and Settings\Ägaren\Lokala inställningar\Application Data\Temporary Projects\Training\main.cs 36 39 Training
    Error 6 Expected class, delegate, enum, interface, or struct C:\Documents and Settings\Ägaren\Lokala inställningar\Application Data\Temporary Projects\Training\main.cs 40 20 Training
    Error 7 Type or namespace definition, or end-of-file expected C:\Documents and Settings\Ägaren\Lokala inställningar\Application Data\Temporary Projects\Training\main.cs 46 8 Training
    Error 8 Invalid expression term '' C:\Documents and Settings\Ägaren\Lokala inställningar\Application Data\Temporary Projects\Training\main.cs 14 26 Training
    Error 9 ; expected C:\Documents and Settings\Ägaren\Lokala inställningar\Application Data\Temporary Projects\Training\main.cs 14 27 Training
    Error 10 ; expected C:\Documents and Settings\Ägaren\Lokala inställningar\Application Data\Temporary Projects\Training\main.cs 14 43 Training
    Error 11 ; expected C:\Documents and Settings\Ägaren\Lokala inställningar\Application Data\Temporary Projects\Training\main.cs 14 52 Training
    Error 12 Invalid expression term '' C:\Documents and Settings\Ägaren\Lokala inställningar\Application Data\Temporary Projects\Training\main.cs 14 53 Training
    Error 13 ; expected C:\Documents and Settings\Ägaren\Lokala inställningar\Application Data\Temporary Projects\Training\main.cs 14 53 Training

    Also, i figured that i might have added the codes on the wrong places, so i tried to download the source, but the source link appears to be broken.

    Thanks in advance,

    -David

    • gregd1024 said

      David – thank you! ;-) The errors are from copy/pasting from the web. It converts the quotes into those “backwards” quotes. Try pasting into notepad first, then copying that into Visual Studio.

      -Greg Dolley

  15. enrique said

    hola

    gracias por el post

    tengo el c# 2008 express edition
    al sacar la ventana de propiedades del proyecto donde deberia salir el output type
    me sale un error

    no se puede mostrar la pagina
    error en la invocacion algo asi y no me muestra el espacio donde deveria salir lo del output type

  16. Anders Nancke-Krogh said

    I have a couple of questions to this framework:
    - Will this framework run on a 64bit OS as a 64bit application? (I need it to access more than 4GB of RAM)
    - Will this framework allow me to chose what GPU that I work with, so that I can load different textures in each GPU?
    - Will this framework allow me to load textures from disk into RAM and then later move it from RAM into VRAM (Video RAM) of any given GPU?
    - Will this framework allow me to read the level of free VRAM in each GPU for textures?
    - Will this framework allow me to dispose textures in a given GPU that I no longer need?

  17. Ronald L. Hammons said

    I tried your C# tutorial. I get the following when I try to compile it using vs2008. This is my first attempt to use C#.
    Thanks for any help.

    System.BadImageFormatException was unhandled
    Message=” is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)”
    Source=”ManagedDirectX_Tutorial1″
    StackTrace:
    at MDX_Tutorial1.MainClass..ctor()
    at MDX_Tutorial1.MainClass.Main() in C:\Users\Ronald\Downloads\Greg Dolley’s DirectX Tutorials\ManagedDirectX_Tutorial1\ManagedDirectX_Tutorial1\main.cs:line 35
    at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
    at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
    at System.Threading.ThreadHelper.ThreadStart()
    InnerException:

    • Dan Scott said

      You get this error because you’re compiling for 64 bit. Under the project properties go to the build tab and change the Platform target to x86. There may be a way to use 64 bit libraries, but I’m new to this too and my application has to be x86 anyway so I’m not going to figure that out now.

      Thanks for the easy to follow example!

  18. Anders Nancke-Krogh said

    Ronald: I moved over to http://slimdx.org/ it works fine for me.

  19. Mark said

    Be sure to compile for x86, because it WILL crash when running in 64 bit mode…

  20. pely said

    It’s work perfect without error ! Thanks !

  21. Mihai said

    I receive two errors:
    ‘MDX_Tutorial1.MainClass.OnPoint(System.Windows.Forms.PaintEventArgs)’: no suitable method found to override
    ‘System.ApplicationException’ does not contain a definition for ‘Run’

    What are about?

  22. Mihai said

    Sorry! I resolved the problems. It was my fault! Excellent tutorial for a beginner!

  23. Dmitri said

    Cool info for a beginner! I have x64 Vista. When set platform target as x86 works lake a charm for me! :)

  24. josema said

    Hi!
    Thanks for these tutorials. They are very helpful for beginners like me.
    I found one issue: “Mixed mode assembly is built against version”,
    but I solved it thanks to this post
    (http://social.msdn.microsoft.com/Forums/eu/vcgeneral/thread/5d1186ec-ad55-4929-b1e4-8806cdc758af)
    , in case anybody else found the same thing.

    Thanks again and keep up with this good work!

  25. mark said

    Many are probably already aware, but I wasn’t able to run this in debug mode in visual studio 2010 at first under win7, it just would hang indefinitely while trying to start the debugger. Running visual studio as administrator solved the problem, hope that saves some time for people who encounter the same problem.

  26. SonicMisora said

    good, I love this.
    but i found i couldn’t load this library in .NET Framework 4.

  27. pluginuri CS…

    Managed DirectX C# Graphics Tutorial 1: Getting Started « Greg Dolley’s Weblog…

  28. ashton said

    private Device m_device = null; //Device says its missing reference :(?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: