Wednesday, April 22, 2009

C# - A class to fade a Form

.Opacity property of form is a number between 0 and 1 (default), then if you change it from 1 to some lower values, you reduced the opacity. In the following sample, the formFader class contains a Static FormFaderWithStep method which accept the target form and another argument between 0 to 255 that show the number of steps which you want to fade your form base on it.


using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace tstBed
{
class formFader
{

public static void FormFaderWithStep(Form frm2Fade,
byte fadeNumOfSteps)
{
if ( (frm2Fade.Opacity != 1) || (fadeNumOfSteps < 1) )
return;
double fadeStep = frm2Fade.Opacity / fadeNumOfSteps;

for( byte iCntr = 0; iCntr < fadeNumOfSteps; iCntr ++ )
{
frm2Fade.Opacity -= fadeStep;
frm2Fade.Refresh();
}
}

}
}


Now just you need to find override version of Dispose event in your form designer code file for your form class (Example: form1.Designer.cs) and add a line to call the fader method, for example: formFader.FormFaderWithStep(this, 100);

protected override void Dispose(bool disposing)
{
formFader.FormFaderWithStep(this, 100);
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

Share/Bookmark

No comments: