原理很简单,在当程序退出的时候,反复设置窗口的透明度,逐渐降低直到循环结束。
①建立MFC基于对话框应用程序,命名Fade
②在FadeDlg.h中加一个句柄,两个函数声明
// 载入user32.dll时用的句柄
HINSTANCE hUserDll;
// 将对话框慢慢透明关掉
void CloseSmoothly(void);
// 设置对话框透明度
BOOL SetTransparent(HWND hWnd, COLORREF crKey, BYTE bAlpha, DWORD dwFlags);
③添加函数定义
在OnInitDialog()中加入
//载入User32.Dll
hUserDll = ::LoadLibrary("USER32.dll");
// 改变对话框风格,为关闭对话框逐渐消失做准备
::SetWindowLong(m_hWnd, GWL_EXSTYLE, ::GetWindowLong(m_hWnd, GWL_EXSTYLE) | 0x00080000 );
SetTransparent(m_hWnd, 0, 255 , 0x00000002 );
其他函数定义如下:
//----------------------------------------------------------------------------------
// 通过呼叫SetLayeredWindowAttributes函数,将窗口设置为渐变透明
//----------------------------------------------------------------------------------
BOOL CFadeDlg::SetTransparent(HWND hWnd, COLORREF crKey, BYTE bAlpha, DWORD dwFlags)
{
BOOL bRet = TRUE;
typedef BOOL (WINAPI* lpfnSetTransparent)(HWND hWnd, COLORREF crKey, BYTE bAlpha, DWORD dwFlags);
// 检查User32.dll是否载入.
if ( hUserDll )
{
lpfnSetTransparent pFnSetTransparent = NULL;
// 调用API函数SetLayeredWindowAttributes
pFnSetTransparent = (lpfnSetTransparent)GetProcAddress(hUserDll, "SetLayeredWindowAttributes");
if (pFnSetTransparent )
bRet = pFnSetTransparent(hWnd, crKey, bAlpha, dwFlags);
else
bRet = FALSE;
}
return bRet;
}
void CFadeDlg::OnClose()
{
CloseSmoothly();
if ( hUserDll )
::FreeLibrary( hUserDll );
CDialog::OnClose();
}
//----------------------------------------------------------------------------------
// 循环调用SetTransparent,将窗口设置为透明
//----------------------------------------------------------------------------------
void CFadeDlg::CloseSmoothly(void)
{
for(int nPercent=150; nPercent >= 0 ;nPercent--)
SetTransparent(m_hWnd, 0, 255 * nPercent/150, 0x00000002);
}