網上找的資料本身改了改,在這裏記錄和分享一下,主要是TransparentWnd函數。函數
在子類的OnShowWindow函數中調用 ShowWindowAlpha()this
#pragma once template<class T> class CPopupDlgBaseT { typedef BOOL (WINAPI *LPFNSETLAYEREDWINDOWATTRIBUTES) (HWND hwnd,COLORREF crKey,BYTE bAlpha,DWORD dwFlags); public: void ShowWindowAlpha() { T* pT = static_cast<T*>(this); CWnd* pParentWnd = pT->GetParent();
if (NULL != pParentWnd)
{ CRect rc; pParentWnd->GetClientRect(&rc); pParentWnd->ClientToScreen(&rc); pT->MoveWindow(&rc);
} TransparentWnd(pT->m_hWnd, 150); } private: BOOL TransparentWnd(HWND hwnd, BYTE byAlpha) { long lStyle; HMODULE hModule; BOOL bRet; LPFNSETLAYEREDWINDOWATTRIBUTES lpSetLayeredWindowAttributes; if(FALSE == IsWindow(hwnd)) { MessageBox(hwnd, TEXT("窗口句柄無效!"), NULL, 0); return FALSE; } hModule = (HMODULE)LoadLibrary(TEXT("user32.dll")); if(hModule) { lpSetLayeredWindowAttributes = (LPFNSETLAYEREDWINDOWATTRIBUTES) GetProcAddress(hModule, "SetLayeredWindowAttributes"); if(!lpSetLayeredWindowAttributes) { MessageBox(hwnd, TEXT("未找到API SetLayeredWindowAttributes的地址!"), NULL, MB_OK); return FALSE; } } lStyle = GetWindowLong(hwnd, GWL_EXSTYLE); if(!lStyle) { MessageBox(hwnd, TEXT("獲取窗口擴展樣式失敗!"), NULL, MB_OK); return FALSE; } lStyle = lStyle | WS_EX_LAYERED; bRet = SetWindowLong(hwnd, GWL_EXSTYLE, lStyle); if(!bRet) { MessageBox(hwnd, TEXT("設置窗口擴展樣式失敗!"), NULL, MB_OK); return FALSE; } bRet = lpSetLayeredWindowAttributes(hwnd, 0, byAlpha, LWA_ALPHA); if(!bRet) { MessageBox(hwnd, TEXT("設置窗口透明度失敗!"), NULL, MB_OK); return FALSE; } ::RedrawWindow(hwnd, NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN); FreeLibrary(hModule); return TRUE; } };