首页 > 代码库 > MFC 对话框透明效果

MFC 对话框透明效果

网上找的资料自己改了改,在这里记录和分享一下,主要是TransparentWnd函数。

在子类的OnShowWindow函数中调用 ShowWindowAlpha()

#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();
        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;
    }
};

 

MFC 对话框透明效果