用MFC实现窗体透明

时间:2022-03-08 10:08:01

使用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); 
}