如何在子控件上使用WS_EX_LAYERED

pob*_*oby 3 winapi visual-c++

从Windows 8开始,WS_EX_LAYERED可以在子控件上使用,(因此称MSDN)。但是我一直无法使其工作。在下面的代码中,我试图使子控件成为半透明的,但是在控件上使用WS_EX_LAYERED时,没有任何效果。

int APIENTRY wWinMain(_In_ HINSTANCE hInst, _In_opt_ HINSTANCE hPrevInst, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
{
    WNDCLASSEX wc = {};

    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInst;
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wc.lpszClassName = _T("main");
    wc.hCursor = LoadCursor(0, IDC_ARROW);
    RegisterClassEx(&wc);

    HWND MWhwnd = CreateWindowEx(NULL, _T("main"), _T(""),
       WS_OVERLAPPEDWINDOW| WS_CLIPCHILDREN,
       CW_USEDEFAULT, 0, CW_USEDEFAULT,0, NULL, NULL, hInst, NULL);

    wc.lpfnWndProc = WndProcPanel;
    wc.lpszClassName = _T("CPanel");
    wc.style = NULL;
    RegisterClassEx(&wc);

    HWND Panelhwnd = CreateWindowEx(WS_EX_LAYERED, _T("CPanel"), _T(""), 
       WS_VISIBLE | WS_CHILD | WS_CLIPSIBLINGS| WS_CLIPCHILDREN,
       100, 10, 400, 400, MWhwnd, NULL, hInst, NULL);

    COLORREF crefKey = RGB(0, 255, 0);
    SetLayeredWindowAttributes(Panelhwnd, crefKey, 155, LWA_ALPHA);

    ShowWindow(MWhwnd, nCmdShow);   
Run Code Online (Sandbox Code Playgroud)

在此示例中,我使用的是自定义控件,但尝试使用的WC_BUTTON结果相同。控件无法绘制。但是我可以使主窗口透明而没有问题。

使用WINDOWS 10和VS2015以及普通的win32(没有MFC,ATL等)

pob*_*oby 5

感谢链接@Hans建议我找到了答案。需要一个清单条目,该条目至少指定Windows 8兼容性(仅从Windows 8开始才支持子分层)。以下内容应作为清单文件提供给任何想使用分层子窗口的人。

<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"> 
    <application>
      <!--The ID below indicates app support for Windows 8 -->
      <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
    </application>
  </compatibility>
  <dependency>
    <dependentAssembly>
        <assemblyIdentity
            type="win32"
            name="Microsoft.Windows.Common-Controls"
            version="6.0.0.0"
            processorArchitecture="*"
            publicKeyToken="6595b64144ccf1df"
            language="*"
        />
    </dependentAssembly>
  </dependency>
</assembly>
Run Code Online (Sandbox Code Playgroud)

为了完整起见,我包含了整个文件,但相关的标记是<compatibility>指定Windows 8 GUID 的元素。

您也可以声明与其他OS版本的兼容性,如docs页面“ 针对Windows的应用程序 ”中所述。