效果:
1.定义两个个定时器ID
#define ID_TIMER_DISPLAY_DELAY 30 #define ID_TIMER_DISPLAY_CLOSE 40
2.添加一个成员函数和成员变量
void SetAlpha(HWND hWnd,int Alpha); int m_nFlag ;
void CPopUpWnd::SetAlpha(HWND hWnd,int Alpha)
{
HINSTANCE hInst = LoadLibrary(L"User32.DLL");
if(hInst)
{
typedef BOOL (WINAPI *MYFUNC)(HWND,COLORREF,BYTE,DWORD);
MYFUNC fun = NULL;
//取得SetLayeredWindowAttributes函数指针
fun=(MYFUNC)GetProcAddress(hInst, "SetLayeredWindowAttributes");
if(fun)fun(hWnd,0,Alpha,2);
FreeLibrary(hInst);
}
}
3.修改窗口属性
void CPopUpWnd::OnPrepare() { //直接显示在右下角 MoveSelfWindow(); //修改窗口属性为了窗口透明度 SetWindowLong(m_hWnd,GWL_EXSTYLE,GetWindowLong(m_hWnd,GWL_EXSTYLE)^0x80000);
//3秒后改变窗口透明度
SetTimer(m_hWnd,ID_TIMER_DISPLAY_DELAY,3000,NULL);
}
4.在定时器响应函数里
LRESULT CPopUpWnd::OnTimer(UINT uMsg, WPARAM wParam, LPARAM lParam,BOOL& bHandled) { switch(wParam) {//多个定时器 case ID_TIMER_DISPLAY_DELAY: KillTimer(m_hWnd,ID_TIMER_DISPLAY_DELAY); SetTimer(m_hWnd,ID_TIMER_DISPLAY_CLOSE,60,NULL); break; case ID_TIMER_DISPLAY_CLOSE: { if(m_nFlag < 255) { m_nFlag+= 5; SetAlpha(m_hWnd,255-m_nFlag); } else { KillTimer(m_hWnd,ID_TIMER_DISPLAY_CLOSE); Close(IDCLOSE); m_nFlag = 0; } } break; } return 0; }
5.窗口渐变关闭过程中,鼠标经过窗口,关闭定时器,窗口恢复原状
LRESULT CPopUpWnd::OnMouseEnter(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { ..... //KillTimer(m_hWnd,ID_TIMER_DISPLAY_DELAY); KillTimer(m_hWnd,ID_TIMER_DISPLAY_CLOSE); if (m_nFlag < 255) { SetAlpha(m_hWnd,255); } .... return 0; }
6.鼠标出了窗口,开启定时器继续渐变关闭窗口
LRESULT CPopUpWnd::OnMouseLeave(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { ..... SetTimer(m_hWnd,ID_TIMER_DISPLAY_CLOSE,30,NULL); m_nFlag = 0; .... return 0; }