WINDOWS上的透明窗口实现

来源:互联网 发布:英语partner交流软件 编辑:程序博客网 时间:2024/05/22 00:43

http://mydone.bokee.com/178980.html(原文)

[转者注]实现局部透明窗口一般有两种方法

1 用SetLayeredWindowAtrribute 来设置具备WS_EX_LAYERED属性的Popup窗口具有透明效果(只对popup窗口有效,子窗口不能使用)。

2 创建异形窗口,并自画窗口(要做半透时效果,自己处理混合)。这种参考[http://www.codeguru.com/Cpp/misc/misc/graphics/article.php/c391]

#define LWA_COLORKEY 1
#define LWA_ALPHA 2
#define WS_EX_LAYERED 0x00080000

typedef BOOL (WINAPI *lpfn) (HWND hWnd, COLORREF cr, BYTE bAlpha, DWORD dwFlags);
lpfn g_pSetLayeredWindowAttributes;

在初试化过程中做:

 HMODULE hUser32 = GetModuleHandle(_T("USER32.DLL"));
 g_pSetLayeredWindowAttributes = (lpfn)GetProcAddress(hUser32, "SetLayeredWindowAttributes");

假如点击Button1做透明效果:

void CHookTest_MFCDlg::OnButton1()
{
 if (g_pSetLayeredWindowAttributes != NULL) {
  HWND hWnd = GetSafeHwnd();
  LONG lWindowLong = GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_LAYERED;
  ::SetWindowLong(hWnd, GWL_EXSTYLE, lWindowLong);
  g_pSetLayeredWindowAttributes(hWnd, 0x00ffffff, (BYTE)192, 2);
  ::RedrawWindow(hWnd, NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
 }
}

参数描述:

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

Syntax

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.



Remarks

Note that once SetLayeredWindowAttributes has been called for a layered window, subsequent UpdateLayeredWindow calls will fail until the layering style bit is cleared and set again.

For more information, see Using Layered Windows.

Function Information

user32.dll Declared in Winuser.h, include Windows.h User32.lib Windows 2000

转者注: 此处可以通过UpdateLayeredWindow (绑定单一图片)来使用窗口透明,它与SetLayeredWindowAttributes 的不同之处在于“绑定的hdc”位图是变化的,所以每次hdc变化后要调用一次此函数。