21xrx.com
2025-04-15 12:26:18 Tuesday
文章检索 我的文章 写文章
C++中使用WebView2实现透明效果
2023-07-11 12:09:10 深夜i     45     0
C++ WebView2 透明效果

WebView2是一种基于Chromium和Microsoft Edge的新型Web视图控件,目前已被纳入了Windows 10 SDK中。它能够让开发者把Web内容嵌入到任何Win32应用程序中,并同时提供了强大的Web API,以增强Web应用程序的功能。

在使用WebView2时,经常需要实现透明效果,这是很常见的需求之一。本篇文章将介绍如何在C++中使用WebView2实现透明效果。

首先,我们需要创建一个Win32窗口,并将WebView2控件作为子窗口嵌入该窗口中。然后,我们需要为WebView2控件设置扩展窗口风格。

如下所示是代码示例:

c++
// 初始化WebView2控件
CreateCoreWebView2EnvironmentWithOptions(nullptr, nullptr, nullptr,
  Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
    [hwnd](HRESULT result, ICoreWebView2Environment* env) -> HRESULT {
      if (env) {
        env->CreateCoreWebView2Controller(hwnd, Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(
          [hwnd](HRESULT result, ICoreWebView2Controller* controller) -> HRESULT {
            if (controller) {
              //设置透明效果
              SetWindowLongPtr(hwnd, GWL_EXSTYLE, GetWindowLongPtr(hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
              SetLayeredWindowAttributes(hwnd, 0, 255, LWA_ALPHA);
              RECT bounds;
              GetClientRect(hwnd, &bounds);
              controller->put_Bounds(bounds);
            }
            return S_OK;
          }).Get());
      }
      return S_OK;
    }).Get());

在上述代码中,我们调用CreateCoreWebView2EnvironmentWithOptions函数创建CoreWebView2环境,并创建CoreWebView2Controller提供了对Web浏览器功能的访问。然后,我们给创建的控制器设置“Bounds”属性,以便使WebView2控件占据整个窗口。

最后,在设置完“Bounds”属性之后,我们需要调用SetWindowLongPtr和SetLayeredWindowAttributes函数实现窗口透明效果。

在这里,我们调用SetWindowLongPtr函数来设置WS_EX_LAYERED扩展窗口风格,使得窗口有了透明的效果;同时,还需调用SetLayeredWindowAttributes函数来设置窗口透明度。

总结来说,实现WebView2控件的透明效果并不难,只需要在创建控件时,为其设置扩展窗口风格即可。同时,对于不同类型的窗口,设置透明效果的方式也会有所不同。因此,开发者需要根据实际需要进行调整和优化。

  
  

评论区

    相似文章