Wednesday, August 23, 2006

Supersimple GDI+ graphics acceleration

I wanted to learn Direct3D.. Actually, all I wanted was to experiment with a 2D scroller game, but I figured out from browsing the net that it would require me to have a look at the 3D library.
I dind't have the time and forgot about it.

A few months later I am making a HTPC type of software. Sure I use DirectX for audio, but it would be overkill to use Direct3D to write a few text strings and images onto the screen.

In stead, I use GDI+, the good old Graphics object. It's flicker free and quite fast. As a demo, I did a remake of the classic Space Invaders game and it turned out to run quite smooth.

Have a look at the following example, it should get you started:

public class MainForm : Form
private Graphics g;
private Bitmap backbuffer;

public MainForm()
backbuffer = new Bitmap(this.Width, this.Height);
g = Graphics.FromImage(backbuffer);

// All painting will occur in the Paint event handler
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint |
ControlStyles.OptimizedDoubleBuffer, true);

private void MainForm_Paint(object sender, PaintEventArgs e)

// Draw stuff here

// Flip the backbuffer onto the screen
e.Graphics.DrawImage(backbuffer, new Point(0, 0));

// Draw graphics again