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

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值