IDCompositionDevice::CreateSurfaceFromHwnd method

Creates a wrapper object that represents the rasterization of a layered window, and that can be associated with a visual for composition.


HRESULT CreateSurfaceFromHwnd(
  [in]  HWND     hwnd,
  [out] IUnknown **surface


hwnd [in]

Type: HWND

The handle of the layered window for which to create a wrapper. 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.

surface [out]

Type: IUnknown**

The new composition surface object. This parameter must not be NULL.

Return value


If the function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code. See DirectComposition Error Codes for a list of error codes.


You can use the surface pointer in calls to the IDCompositionVisual::SetContent method to set the content of one or more visuals. After setting the content, the visuals compose the contents of the specified layered window as long as the window is layered. If the window is unlayered, the window content disappears from the output of the composition tree. If the window is later re-layered, the window content reappears as long as it is still associated with a visual. If the window is resized, the affected visuals are re-composed.

The contents of the window are not cached beyond the life of the window. That is, if the window is destroyed, the affected visuals stop composing the window.

If the window is moved off-screen or resized to zero, the system stops composing the content of visuals. You should use the DwmSetWindowAttribute function with the DWMWA_CLOAK flag to "cloak" the layered child window when you need to hide the original window while allowing the system to continue to compose the content of the visuals. For more information, see How to animate the bitmap of a layered child window and DirectComposition layered child window sample.


The following code snippet creates a wrapper object that represents the rasterization of a layered window.

IDCompositionVisual *pVisual = nullptr;
IUnknown *pSurface = nullptr;

// Create a visual. g_pDevice is the IDCompositionDevice pointer of a 
// device object created earlier.
hr = g_pDevice->CreateVisual(&pVisual);

if (SUCCEEDED(hr))
    // Create a surface that contains the image of the layered child 
    // window identified by the g_hwndChild window handle (HWND). 
    hr = g_pDevice->CreateSurfaceFromHwnd(g_hwndChild, &pSurface);

if (SUCCEEDED(hr))
    // Set the content of the Control child visual.
    hr = pVisual->SetContent(pSurface);


Minimum supported client

Windows 8 [desktop apps only]

Minimum supported server

Windows Server 2012 [desktop apps only]







See also