1. 程式人生 > >用MFC實現窗體透明

用MFC實現窗體透明

使用SetLayeredWindowAttributes可以方便的製作透明窗體,此函式在w2k以上才支援,而且如果希望直接使用的話,可能需要下載最新的SDK。不過此函式在w2k的user32.dll裡有實現,所以如果你不希望下載巨大的sdk的話,可以直接使用GetProcAddress獲取該函式的指標。

以下是MSDN上的原內容,我會加以解釋。

The SetLayeredWindowAttributes function sets the opacity and transparency color key of a layered window.

BOOL SetLayeredWindowAttributes(

    HWND hwnd,
    COLORREF crKey,
    BYTE bAlpha,
    DWORD dwFlags
);
Parameters

hwnd
[in] Handle to the layered window. A layered window is created by specifying WS_EX_LAYERED when creating the window with the CreateWindowEx function or by setting WS_EX_LAYERED via SetWindowLong after the window has been created.

crKey
[in] COLORREF structure that specifies the transparency color key to be used when composing the layered window. All pixels painted by the window in this color will be transparent. To generate a COLORREF, use the RGB macro.


bAlpha
[in] Alpha value used to describe the opacity of the layered window. Similar to the SourceConstantAlpha member of the BLENDFUNCTION structure. When bAlpha is 0, the window is completely transparent. When bAlpha is 255, the window is opaque.


dwFlags
[in] Specifies an action to take. This parameter can be one or more of the following values.
LWA_COLORKEY
Use crKey as the transparency color.
LWA_ALPHA
Use bAlpha to determine the opacity of the layered window.


Return Value

If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.

詳細解說

引數1、主要說的是所要設定的窗體必須是WS_EX_LAYERED格式,設定方法如下:

           //設定窗體為WS_EX_LAYERED格式

SetWindowLong(this->GetSafeHwnd(),GWL_EXSTYLE, 

GetWindowLong(this->GetSafeHwnd(),GWL_EXSTYLE)^0x80000);     

//其實0x80000 == WS_EX_LAYERED

引數2、意思是可以設定指定的顏色為透明色,通過RGB巨集設定。

引數3、可以簡單的理解為窗體透明的程度範圍為0~255(0為完全透明,255不透明)。

引數4、可以取兩個值LWA_COLORKEY (0x1)和 LWA_ALPHA(0x2),如下:

取值為LWA_ALPHA即等於2時,引數2無效,通過引數3決定透明度.

取值為LWA_COLORKEY即等於1時,引數3無效,引數2指定的顏色為透明色,其他顏色則正常顯示.

把以下程式碼放OnInitDialog中即可實現半透明窗體

SetWindowLong(this->GetSafeHwnd(), GWL_EXSTYLE, 

GetWindowLong(this->GetSafeHwnd(), GWL_EXSTYLE)^WS_EX_LAYERED);

HINSTANCE hInst = LoadLibrary("User32.DLL"); //顯式載入DLL
if (hInst) 
{            
typedef BOOL(WINAPI *MYFUNC) (HWND,COLORREF,BYTE,DWORD);          
MYFUNC fun = NULL;

//取得SetLayeredWindowAttributes函式指標     
fun=(MYFUNC)GetProcAddress(hInst, "SetLayeredWindowAttributes"); 
if (fun)

fun(this->GetSafeHwnd(), 0, 128, 2);     //通過第三個引數來設定窗體透明程度
FreeLibrary(hInst); 
}