<!-- Link to source file download -->
Download source files - 4 Kb
<!-- Link to demo file download -->
Download demo project - 28 Kb
<!-- Article image -->
<!-- Add the rest of your HTML here -->
One of the attractive new features of Windows 2000 is the menu and other selections that fade away instead
of just disappearing. To see this in operation you need to select "Use transition effects for menus and tooltips"
on the "Effects" tab of the Display Properties dialog and then select "Fade effect" in the combo box.
In this article I present a simple MFC class that allows you to apply a similar fading effect to any window
you choose - with only one line of code! Don't just close a window - have it fade away!
The effect is most appropriate to small windows; I use it most often for splash
windows, about boxes and other small dialogs.
To use the code you just add the FaderWnd source and header files to your MFC project, include the header
in the relevant source file and construct a
CFaderWnd when you want your window to fade. The
object itself takes care of fading your window and then destroying and deleting itself.
The only code you need to write is
new CFaderWnd(this). Once the
CFaderWnd is constructed
you can destroy or hide your window, or call
EndDialog if the window is a modal dialog.
For example, a modeless dialog (or it could be any child window):
or a modal dialog:
How it works
CFaderWnd uses the new layered windows feature and the
UpdateLayeredWindow API function.
The constructor creates a new topmost window with the
WS_EX_LAYERED style (among others) and with the same size and position
as the source window (the window to be faded). It then uses
UpdateLayeredWindow to fill the new window
with a bitmap that is an exact copy of the source window. It also sets up a timer. When the constructor returns the source window
can be destroyed (or hidden) and the new window remains visible.
On each timer message
UpdateLayeredWindow again with a smaller value of alpha. Reducing
the alpha value makes the window increasingly translucent. When alpha is at or very near zero
CFaderWnd destroys the window and
PostNcDestroy deletes the
CFaderWnd constructor takes three parameters; it looks like
CFaderWnd(CWnd *pWndToFade, UINT nFadeTime = 2000, BYTE byAlpha = 255);
The second and third parameters are optional; the examples above all use the default values for these parameters.
For obvious reasons (and if they're not obvious you shouldn't be reading this) the first parameter, which specifies
the window to fade, must be supplied.
This is a pointer to the source window (the window to be faded).
|This is a number of milliseconds for the whole duration of
the fade. The default value gives a 2 second fade.
|This is the alpha value at which to start the fade. The
default value of 255 represents starting with a fully opaque window. You
might choose to start at 127, for example, so that the window immediately
becomes semi-transparent and then fades from there.