When using Xna’s excellent classes to create a game, sometimes you don’t want to use the Game class, but you rather want to implement this yourself. This requires a custom window, along with a custom game loop.

This is possible using the GraphicsDevice, which is handled for you in the Game class, but it can also be instantiated manually.

First, you’ll need to create a window to contain the render target.

Form mainWindow = new Form();  
mainWindow.Width = 800;  
mainWindow.Height = 600;  

You can actually use any type of container control, which can be useful if you’d like to incorporate other WinForms controls in your project, such as buttons.

Now the GraphicsDevice can be instantiated, along with a set of parameters.

PresentationParameters presParams = new PresentationParameters();  
presParams.BackBufferWidth = 800;  
presParams.BackBufferHeight = 600;  
presParams.DeviceWindowHandle = mainWindow.Handle;  
presParams.IsFullScreen = false;  

GraphicsDevice graphicsDevice = new GraphicsDevice(GraphicsAdapter.DefaultAdapter, GraphicsProfile.HiDef, presParams);
Feel free to play around with these settings, they control most of the settings you’ll find at any graphics settings menu, such as Multisampling (Antialiasing).

Now the graphics device is ready to use. What we need now is a simple game loop. The WinForms Application class has an ‘Idle’ event, which we can use for this.

public static void main(String[] args)  
    // Above code goes here<br>    // Note that the GraphicsDevice and the Form should be members,
    // so they can be accessed from the Application_Idle() method

    Application.Idle += new EventHandler(Application_Idle);


private static void Application_Idle(object sender, EventArgs e)  
    // This method gets called as much as possible,
    // Calls to Update() and Draw() can be made here


    // Drawing code here


    // Causes the window to redraw and call the Idle event again when it’s done

This is a very simple game loop, which you’ll probably want to extend with a nice Draw() and Update() method. First of all, the render target is cleared with the familiar CornflowerBlue. Then you can draw whatever you want to draw, for example using the SpriteBatch. Finally, the graphics device is instructed to present its rendertarget to the window.