Closing A Window Smoothly

Wednesday May 8th 2002 by Mohammad A. Salah

Enhance the user interface for your application by closing its windows in a smoothly way--make your window disappear (fade out) slowly while its closing.

Environment: VC6, win2000, winXP

Enhance the user interface for your application by closing its windows in a smoothly way--make your window disappear slowly (fade out) while its closing.


The technique is very simple. While closing the window, just loop and increase transparency value to the window each loop until the window disappear completely. The API function that responsible to make the window transparent is:

SetLayeredWindowAttributes(HWND, COLORREF, BYTE,DWORD)

The third parameter is responsible for determine the degree of transparency, by increase this value each time the window will disappear slowly. The SetLayeredWindowAttributes(...) function is found in USER32.DLL, so you need to load this dll before you can use it. Here is the code:

First Step: you must change the window style to a layered style By calling SetWindowLong(...) API function. Use this step in the OnInitDialog() function in a dialog based application or in the OnCreate() function in a Document/View application:

                   ::GetWindowLong(m_hWnd, GWL_EXSTYLE) | WS_EX_LAYERED);

Then Call:

SetTransparent( m_hWnd, 0, 255 , LWA_ALPHA );

with a bAlpha value equal 255. The implementation of the function look like this:

// This function sets the transparency layered window 
// by calling SetLayeredWindowAttributes API function.

BOOL SetTransparent(HWND hWnd, COLORREF crKey, 
                    BYTE  bAlpha, DWORD dwFlags)
  BOOL bRet = TRUE;
  typedef BOOL (WINAPI* lpfnSetTransparent)(HWND hWnd,
                                       COLORREF crKey,
                                          BYTE bAlpha,
                                       DWORD dwFlags);

  // Check that "USER32.dll" library has been 
  // loaded successfully...
  if ( m_hUserDll )
    lpfnSetTransparent pFnSetTransparent = NULL;
    pFnSetTransparent = 

    if (pFnSetTransparent )
       bRet = pFnSetTransparent(hWnd, crKey, bAlpha, dwFlags);
       bRet = FALSE;
  } // if( m_hUserDll )

   return bRet;
} // End of SetTransparent function

Second Step: call the CloseSmoothly() function in the OnClose() function. The CloseSmoothly() function will look like this:

 void CloseSmoothly()
  // Increase transparency one percent each time...
  for(int nPercent=100; nPercent >= 0 ;nPercent--)
     SetTransparent( m_hWnd, 0, 255 * nPercent/100, LWA_ALPHA);


Download demo project - 4 Kb
Download source - 13 Kb
Mobile Site | Full Site
Copyright 2018 © QuinStreet Inc. All Rights Reserved