Adding event handlers
So far we have no way of exiting the program or managing any loss of focus. The first problem is easily solved by adding a key-press handler and detecting the escape key as shown here.
private void f_keydown(Object sender,System.Windows.Forms.KeyEventArgs e)
{
if(e.KeyCode==Keys.Escape)
{
GameOver();
Application.Exit();
}
}
In order for this to work, you will also need to add the following line to the form constructor, following the COM initialisation sequence:
this.KeyDown+=new System.Windows.Forms.KeyEventHandler(this.f_keydown);
Now we can exit the game loop with the ESC key, but if the window is minimised or another application steals the focus, our DirectDraw surfaces are lost. To resolve this, we need to add another event handler to the form’s constructor.
this.Load += new System.EventHandler(this.Restore);
This line should appear after the call to this.Show(), but before creating the DirectDraw device, as the latter is required to restore any lost surfaces. The restore function disposes of the lost device and its surfaces before re-initialising them. This will give us a fresh new device and its surfaces when we regain focus, but there is still the problem of dealing with the lost surfaces when focus is lost. If the window is minimised during the RenderSurface function, an exception will be thrown when the surfaces are suddenly made unavailable. We can catch this exception and perform any tidying up required as shown here.
public void RenderSurface()
{
try
{
ddSurface1.ColorFill(Color.Black);
ddSurface1.Flip(ddSurface2, FlipFlags.Wait);
}
catch
{
ddSurface1.Dispose();
Initialise();
}
}
This Try/Catch block will prevent the loss of focus from throwing an exception when the game tries to flip to a non-existent surface. The application will now compile, run and keep running when focus to the main window is lost and regained.