Programming - Games - 2D - using DX9 and C#

This toturial was written for me by Imran Khan (imranahmedkhan82@hotmail.com, iak1982@yahoo.com).
Copyright (c) 2004 is owned by Martin Baker

Restoring Lost Surfaces:

We have Learn about Surfaces but there is one problem with them , when your application got minimize all the surfaces and devices you initlialize will be lost and you will see nothing.In this Section We will show the solution of this problem.

Its a continuation of the previous program. We will change the Constructor of form1 class, Showsurface( ) method and add a new method of ' GFocus ' .

Let Start with Constructor.

public Form1(): base()
{
InitializeComponent();
this.Show();
this.Load += new System.EventHandler(this.GFocus);
dddevice=new Device();
dddevice.SetCooperativeLevel(this,CooperativeLevelFlags.FullscreenExclusive);
Init();
Gameloop();
}

As you see the method is same as previous we just add one line ' this.Load += new System.EventHandler(this.GFocus); ' . This adds handler to the GotFocus event (we will define GotFocus Handler later) When the application Lost focus the device and surfaces lost, so the next time the form comes up we have to reinitialize the device. This is where the GotFocus event must be added to the form.

now GotFocus Handler.

public void GFocus(object sender, System.EventArgs e )
{
ending();
Form1 newform=new Form1();
}

Its a small and easy event, When the form lost and then got focus this event will be call. As first line will Destroy all the objects of devices, surfaces and then calling constructor of the form1 by making instance of form1. As the constructor call it initialize the surfaces and devices by calling Init( ).

Now ShowSurface ( ) method.

public void ShowSurface()
{

try
{
ssurface.ColorFill(Color.White);
psurface.Flip(ssurface, FlipFlags.Wait);
}
catch
{
psurface.Dispose();
Init();
}

}

We add just Try and Catch Block in this Method to Catch the Exception of Lost Surface.

The Explanation of Exception is this, first time this function will work without try catch but when it lost focus , it will lost all the surfaces and again when it got focused by the user, it try to fill the surface (1st line) and then flip the surface (2nd line). This will throw Exception that the Surface is not present. To handle this problem Use try catch block and in Catch , reinitialize the surfaces and devices.

Now when you run the program you will see a White screen, When you minimize it by pressing ' Alt + Tab ' and then again focus this window , YOU WILL STILL SEE THE SAME WHITE SCREEN.

next: images


metadata block
see also:
Correspondence about this page

This site may have errors. Don't use for critical systems.

Copyright (c) 1998-2022 Martin John Baker - All rights reserved - privacy policy.