다음을 통해 공유


화면 캡처

Windows 10 버전 1803부터 Windows.Graphics.Capture 네임스페이스는 디스플레이 또는 애플리케이션 창에서 프레임을 획득하고, 비디오 스트림 또는 스냅샷을 만들어 공동 작업 및 대화형 환경을 빌드하는 API를 제공합니다.

화면 캡처를 사용하면 개발자는 최종 사용자가 캡처할 디스플레이 또는 애플리케이션 창을 선택할 수 있도록 보안 시스템 UI를 호출하고, 시스템에서 활성 캡처된 항목 주위에 노란색 알림 테두리를 그립니다. 여러 동시 캡처 세션의 경우 캡처되는 각 항목 주위에 노란색 테두리가 그려집니다.

비고

화면 캡처 API는 Windows 디바이스 및 Windows Mixed Reality 몰입형 헤드셋에서만 지원됩니다.

이 문서에서는 디스플레이 또는 애플리케이션 창의 단일 이미지를 캡처하는 것에 대해 설명합니다. 화면에서 비디오 파일로 캡처된 프레임을 인코딩하는 방법에 대한 자세한 내용은 비디오 화면 캡처를 참조하세요.

화면 캡처 기능 추가

Windows.Graphics.Capture 네임스페이스에 있는 API에는 애플리케이션 매니페스트에서 선언해야 하는 일반적인 기능이 필요합니다.

  1. 솔루션 탐색기에서 Package.appxmanifest을 엽니다.
  2. 기능 탭을 선택합니다.
  3. 그래픽 캡처확인하세요.

그래픽 캡처

시스템 UI를 시작하여 화면 캡처 시작

시스템 UI를 시작하기 전에 애플리케이션이 현재 화면 캡처를 수행할 수 있는지 확인할 수 있습니다. 디바이스가 하드웨어 요구 사항을 충족하지 않거나 캡처 대상으로 지정된 애플리케이션이 화면 캡처를 차단하는 경우를 포함하여 애플리케이션이 화면 캡처를 사용하지 못할 수 있는 몇 가지 이유가 있습니다. GraphicsCaptureSession 클래스에서 IsSupported 메서드를 사용하여 UWP 화면 캡처가 지원되는지 확인합니다.

// This runs when the application starts.
public void OnInitialization()
{
    if (!GraphicsCaptureSession.IsSupported())
    {
        // Hide the capture UI if screen capture is not supported.
        CaptureButton.Visibility = Visibility.Collapsed;
    }
}
Public Sub OnInitialization()
    If Not GraphicsCaptureSession.IsSupported Then
        CaptureButton.Visibility = Visibility.Collapsed
    End If
End Sub

화면 캡처가 지원되는 것을 확인했으면 GraphicsCapturePicker 클래스를 사용하여 시스템 선택기 UI를 호출합니다. 최종 사용자는 이 UI를 사용하여 화면 캡처를 수행할 디스플레이 또는 애플리케이션 창을 선택합니다. 선택기는 GraphicsCaptureSession를 만드는 데 사용될 GraphicsCaptureItem 를 반환합니다.

public async Task StartCaptureAsync()
{
    // The GraphicsCapturePicker follows the same pattern the
    // file pickers do.
    var picker = new GraphicsCapturePicker();
    GraphicsCaptureItem item = await picker.PickSingleItemAsync();

    // The item may be null if the user dismissed the
    // control without making a selection or hit Cancel.
    if (item != null)
    {
        // We'll define this method later in the document.
        StartCaptureInternal(item);
    }
}
Public Async Function StartCaptureAsync() As Task
    ' The GraphicsCapturePicker follows the same pattern the
    ' file pickers do.
    Dim picker As New GraphicsCapturePicker
    Dim item As GraphicsCaptureItem = Await picker.PickSingleItemAsync()

    ' The item may be null if the user dismissed the
    ' control without making a selection or hit Cancel.
    If item IsNot Nothing Then
        StartCaptureInternal(item)
    End If
End Function

UI 코드이므로 UI 스레드에서 호출해야 합니다. 애플리케이션의 페이지(예: MainPage.xaml.cs)에 대한 코드 숨김에서 호출할 경우 자동으로 처리되지만, 그렇지 않은 경우에는 다음 코드를 사용하여 UI 스레드에서 강제로 실행할 수 있습니다.

CoreWindow window = CoreApplication.MainView.CoreWindow;

await window.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
    await StartCaptureAsync();
});
Dim window As CoreWindow = CoreApplication.MainView.CoreWindow
Await window.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                 Async Sub() Await StartCaptureAsync())

캡처 프레임 풀 만들기 및 캡처 세션

GraphicsCaptureItem사용하여 D3D 디바이스, 지원되는 픽셀 형식(DXGI_FORMAT_B8G8R8A8_UNORM), 원하는 프레임 수(정수일 수 있음) 및 프레임 크기로 Direct3D11CaptureFramePool 만듭니다. GraphicsCaptureItem 클래스의 ContentSize 속성을 프레임 크기로 사용할 수 있습니다.

비고

Windows HD 색이 활성화된 시스템에서는 콘텐츠 픽셀 형식이 반드시 DXGI_FORMAT_B8G8R8A8_UNORM가 아닐 수도 있습니다. HDR 콘텐츠를 캡처할 때 픽셀 오버클립(즉, 캡처된 콘텐츠가 바래 보임)을 방지하려면, Direct3D11CaptureFramePoolCanvasBitmap같은 대상지를 포함하여 캡처 파이프라인의 모든 구성 요소에 DXGI_FORMAT_R16G16B16A16_FLOAT를 사용하는 것이 좋습니다. 필요에 따라 HDR 콘텐츠 형식 또는 HDR-SDR 톤 매핑에 저장하는 등의 추가 처리가 필요할 수 있습니다. 이 문서에서는 SDR 콘텐츠 캡처를 중점으로 살펴보겠습니다. 자세한 내용은 DirectX를 사용하는 높은 동적 범위 디스플레이 및 고급 색 을 참조하세요.

private GraphicsCaptureItem _item;
private Direct3D11CaptureFramePool _framePool;
private CanvasDevice _canvasDevice;
private GraphicsCaptureSession _session;

public void StartCaptureInternal(GraphicsCaptureItem item)
{
    _item = item;

    _framePool = Direct3D11CaptureFramePool.Create(
        _canvasDevice, // D3D device
        DirectXPixelFormat.B8G8R8A8UIntNormalized, // Pixel format
        2, // Number of frames
        _item.Size); // Size of the buffers
}
WithEvents CaptureItem As GraphicsCaptureItem
WithEvents FramePool As Direct3D11CaptureFramePool
Private _canvasDevice As CanvasDevice
Private _session As GraphicsCaptureSession

Private Sub StartCaptureInternal(item As GraphicsCaptureItem)
    CaptureItem = item

    FramePool = Direct3D11CaptureFramePool.Create(
        _canvasDevice, ' D3D device
        DirectXPixelFormat.B8G8R8A8UIntNormalized, ' Pixel format
        2, '  Number of frames
        CaptureItem.Size) ' Size of the buffers
End Sub

다음으로 GraphicsCaptureItemCreateCaptureSession 메서드에 전달하여, Direct3D11CaptureFramePool에 대한 GraphicsCaptureSession 클래스의 인스턴스를 가져옵니다.

_session = _framePool.CreateCaptureSession(_item);
_session = FramePool.CreateCaptureSession(CaptureItem)

사용자가 애플리케이션 창을 캡처하거나 시스템 UI에 표시하는 데 명시적으로 동의하면 GraphicsCaptureItem 여러 CaptureSession 개체에 연결할 수 있습니다. 이렇게 하면 애플리케이션에서 다양한 환경에 대해 동일한 항목을 캡처하도록 선택할 수 있습니다.

여러 항목을 동시에 캡처하려면 애플리케이션에서 캡처할 각 항목에 대한 캡처 세션을 만들어야 합니다. 캡처할 각 항목에 대해 선택기 UI를 호출해야 합니다.

캡처 프레임 획득

프레임 풀 및 캡처 세션을 만든 상태에서 GraphicsCaptureSession 인스턴스에서 StartCapture 메서드를 호출하여 캡처 프레임을 앱에 보내기 시작하도록 시스템에 알립니다.

_session.StartCapture();
_session.StartCapture()

Direct3D11CaptureFrame 개체에 이러한 캡처 프레임을 획득하려면 Direct3D11CaptureFramePool.FrameArrived 이벤트를 사용할 수 있습니다.

_framePool.FrameArrived += (s, a) =>
{
    // The FrameArrived event fires for every frame on the thread that
    // created the Direct3D11CaptureFramePool. This means we don't have to
    // do a null-check here, as we know we're the only one  
    // dequeueing frames in our application.  

    // NOTE: Disposing the frame retires it and returns  
    // the buffer to the pool.
    using (var frame = _framePool.TryGetNextFrame())
    {
        // We'll define this method later in the document.
        ProcessFrame(frame);
    }  
};
Private Sub FramePool_FrameArrived(sender As Direct3D11CaptureFramePool, args As Object) Handles FramePool.FrameArrived
    ' The FrameArrived event is raised for every frame on the thread
    ' that created the Direct3D11CaptureFramePool. This means we
    ' don't have to do a null-check here, as we know we're the only
    ' one dequeueing frames in our application.  

    ' NOTE Disposing the frame retires it And returns  
    ' the buffer to the pool.

    Using frame = FramePool.TryGetNextFrame()
        ProcessFrame(frame)
    End Using
End Sub

이 이벤트는 새 프레임을 사용할 수 있을 때마다 자주 발생하므로 FrameArrived가능한 경우 UI 스레드를 사용하지 않는 것이 좋습니다. UI 스레드에서 FrameArrived를 수신하도록 선택하는 경우 이벤트가 발생할 때마다 얼마나 많은 작업을 수행하는지 염두에 두어야 합니다.

또는 필요한 모든 프레임을 가져올 때까지 Direct3D11CaptureFramePool.TryGetNextFrame 메서드를 사용하여 프레임을 수동으로 끌어올 수 있습니다.

Direct3D11CaptureFrame 개체에는 ContentSize, SurfaceSystemRelativeTime속성이 포함되어 있습니다. SystemRelativeTime은 다른 미디어 요소를 동기화하는 데 사용할 수 있는 QPC (QueryPerformanceCounter) 시간입니다.

프로세스 캡처 프레임

Direct3D11CaptureFramePool 각 프레임은 TryGetNextFrame호출할 때 체크 아웃되고 Direct3D11CaptureFrame 개체의 수명에 따라 다시 체크 인됩니다. 네이티브 애플리케이션의 경우 Direct3D11CaptureFrame 개체를 해제하면 프레임을 프레임 풀로 다시 체크 인할 수 있습니다. 관리되는 애플리케이션의 경우 Direct3D11CaptureFrame.Dispose(C++에서Close) 메서드를 사용하는 것이 좋습니다. Direct3D11CaptureFrameIClosable 인터페이스를 구현하며, 이는 C# 호출자에게는 IDisposable로 프로젝션됩니다.

애플리케이션은 Direct3D11CaptureFrame 개체에 대한 참조를 저장하지 않아야 하며, 프레임이 다시 체크 인된 후 기본 Direct3D 화면에 대한 참조를 저장해서는 안 됩니다.

프레임을 처리하는 동안 애플리케이션은 Direct3D11CaptureFramePool 개체와 연결된 동일한 디바이스에서 ID3D11Multithread 잠금을 취하는 것이 좋습니다.

기본 Direct3D 표면은 Direct3D11CaptureFramePool 을(를) 만들거나 다시 만들 때 지정된 크기로 항상 유지됩니다. 콘텐츠가 프레임보다 크면 콘텐츠가 프레임 크기로 잘립니다. 콘텐츠가 프레임보다 작으면 프레임의 나머지 부분에 정의되지 않은 데이터가 포함됩니다. 애플리케이션은 정의되지 않은 콘텐츠가 표시되지 않도록 Direct3D11CaptureFrame에 대한 ContentSize 속성을 사용하여 하위 사각형을 복사할 것을 권장합니다.

스크린샷 만들기

이 예제에서는 각 Direct3D11CaptureFrameWin2D API들의 일부인 CanvasBitmap으로 변환합니다.

// Convert our D3D11 surface into a Win2D object.
CanvasBitmap canvasBitmap = CanvasBitmap.CreateFromDirect3D11Surface(
    _canvasDevice,
    frame.Surface);

CanvasBitmap을 얻으면, 이미지 파일로 저장할 수 있습니다. 다음 예제에서는 사용자의 저장된 그림 폴더에 PNG 파일로 저장합니다.

StorageFolder pictureFolder = KnownFolders.SavedPictures;
StorageFile file = await pictureFolder.CreateFileAsync("test.png", CreationCollisionOption.ReplaceExisting);

using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
    await canvasBitmap.SaveAsync(fileStream, CanvasBitmapFileFormat.Png, 1f);
}

항목 크기 조정 또는 디바이스 손실 캡처에 대응

캡처 프로세스 중에 애플리케이션은 Direct3D11CaptureFramePool의 측면을 변경할 수 있습니다. 여기에는 새 Direct3D 디바이스 제공, 프레임 버퍼 크기 변경 또는 풀 내의 버퍼 수 변경이 포함됩니다. 각 시나리오에서는 Direct3D11CaptureFramePool 개체의 Recreate 메서드를 사용하는 것이 권장됩니다.

재생성이 호출되면 모든 기존 프레임이 삭제됩니다. 이는 기본 Direct3D 표면이 애플리케이션에 더 이상 액세스할 수 없는 디바이스에 속하는 프레임을 전달하지 않도록 하기 위한 것입니다. 이러한 이유로다시 호출하기 전에 보류 중인 모든 프레임을 처리하는 것이 현명할 수 있습니다.

이 모든 것을 하나로 모으다.

다음 코드 조각은 UWP 애플리케이션에서 화면 캡처를 구현하는 방법의 엔드 투 엔드 예제입니다. 이 샘플에서는 프런트 엔드에 두 개의 단추가 있습니다. 하나는 Button_ClickAsync호출하고 다른 하나는 ScreenshotButton_ClickAsync호출합니다.

비고

이 코드 조각은 2D 그래픽 렌더링용 라이브러리인 win2D사용합니다. 프로젝트에 대해 설정하는 방법에 대한 자세한 내용은 해당 설명서를 참조하세요.

using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.UI.Composition;
using System;
using System.Numerics;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Graphics;
using Windows.Graphics.Capture;
using Windows.Graphics.DirectX;
using Windows.Storage;
using Windows.UI;
using Windows.UI.Composition;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Hosting;

namespace ScreenCaptureTest
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        // Capture API objects.
        private SizeInt32 _lastSize;
        private GraphicsCaptureItem _item;
        private Direct3D11CaptureFramePool _framePool;
        private GraphicsCaptureSession _session;

        // Non-API related members.
        private CanvasDevice _canvasDevice;
        private CompositionGraphicsDevice _compositionGraphicsDevice;
        private Compositor _compositor;
        private CompositionDrawingSurface _surface;
        private CanvasBitmap _currentFrame;
        private string _screenshotFilename = "test.png";

        public MainPage()
        {
            this.InitializeComponent();
            Setup();
        }

        private void Setup()
        {
            _canvasDevice = new CanvasDevice();

            _compositionGraphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(
                Window.Current.Compositor,
                _canvasDevice);

            _compositor = Window.Current.Compositor;

            _surface = _compositionGraphicsDevice.CreateDrawingSurface(
                new Size(400, 400),
                DirectXPixelFormat.B8G8R8A8UIntNormalized,
                DirectXAlphaMode.Premultiplied);    // This is the only value that currently works with
                                                    // the composition APIs.

            var visual = _compositor.CreateSpriteVisual();
            visual.RelativeSizeAdjustment = Vector2.One;
            var brush = _compositor.CreateSurfaceBrush(_surface);
            brush.HorizontalAlignmentRatio = 0.5f;
            brush.VerticalAlignmentRatio = 0.5f;
            brush.Stretch = CompositionStretch.Uniform;
            visual.Brush = brush;
            ElementCompositionPreview.SetElementChildVisual(this, visual);
        }

        public async Task StartCaptureAsync()
        {
            // The GraphicsCapturePicker follows the same pattern the
            // file pickers do.
            var picker = new GraphicsCapturePicker();
            GraphicsCaptureItem item = await picker.PickSingleItemAsync();

            // The item may be null if the user dismissed the
            // control without making a selection or hit Cancel.
            if (item != null)
            {
                StartCaptureInternal(item);
            }
        }

        private void StartCaptureInternal(GraphicsCaptureItem item)
        {
            // Stop the previous capture if we had one.
            StopCapture();

            _item = item;
            _lastSize = _item.Size;

            _framePool = Direct3D11CaptureFramePool.Create(
               _canvasDevice, // D3D device
               DirectXPixelFormat.B8G8R8A8UIntNormalized, // Pixel format
               2, // Number of frames
               _item.Size); // Size of the buffers

            _framePool.FrameArrived += (s, a) =>
            {
                // The FrameArrived event is raised for every frame on the thread
                // that created the Direct3D11CaptureFramePool. This means we
                // don't have to do a null-check here, as we know we're the only
                // one dequeueing frames in our application.  

                // NOTE: Disposing the frame retires it and returns  
                // the buffer to the pool.

                using (var frame = _framePool.TryGetNextFrame())
                {
                    ProcessFrame(frame);
                }
            };

            _item.Closed += (s, a) =>
            {
                StopCapture();
            };

            _session = _framePool.CreateCaptureSession(_item);
            _session.StartCapture();
        }

        public void StopCapture()
        {
            _session?.Dispose();
            _framePool?.Dispose();
            _item = null;
            _session = null;
            _framePool = null;
        }

        private void ProcessFrame(Direct3D11CaptureFrame frame)
        {
            // Resize and device-lost leverage the same function on the
            // Direct3D11CaptureFramePool. Refactoring it this way avoids
            // throwing in the catch block below (device creation could always
            // fail) along with ensuring that resize completes successfully and
            // isn’t vulnerable to device-lost.
            bool needsReset = false;
            bool recreateDevice = false;

            if ((frame.ContentSize.Width != _lastSize.Width) ||
                (frame.ContentSize.Height != _lastSize.Height))
            {
                needsReset = true;
                _lastSize = frame.ContentSize;
            }

            try
            {
                // Take the D3D11 surface and draw it into a  
                // Composition surface.

                // Convert our D3D11 surface into a Win2D object.
                CanvasBitmap canvasBitmap = CanvasBitmap.CreateFromDirect3D11Surface(
                    _canvasDevice,
                    frame.Surface);

                _currentFrame = canvasBitmap;

                // Helper that handles the drawing for us.
                FillSurfaceWithBitmap(canvasBitmap);
            }

            // This is the device-lost convention for Win2D.
            catch (Exception e) when (_canvasDevice.IsDeviceLost(e.HResult))
            {
                // We lost our graphics device. Recreate it and reset
                // our Direct3D11CaptureFramePool.  
                needsReset = true;
                recreateDevice = true;
            }

            if (needsReset)
            {
                ResetFramePool(frame.ContentSize, recreateDevice);
            }
        }

        private void FillSurfaceWithBitmap(CanvasBitmap canvasBitmap)
        {
            CanvasComposition.Resize(_surface, canvasBitmap.Size);

            using (var session = CanvasComposition.CreateDrawingSession(_surface))
            {
                session.Clear(Colors.Transparent);
                session.DrawImage(canvasBitmap);
            }
        }

        private void ResetFramePool(SizeInt32 size, bool recreateDevice)
        {
            do
            {
                try
                {
                    if (recreateDevice)
                    {
                        _canvasDevice = new CanvasDevice();
                    }

                    _framePool.Recreate(
                        _canvasDevice,
                        DirectXPixelFormat.B8G8R8A8UIntNormalized,
                        2,
                        size);
                }
                // This is the device-lost convention for Win2D.
                catch (Exception e) when (_canvasDevice.IsDeviceLost(e.HResult))
                {
                    _canvasDevice = null;
                    recreateDevice = true;
                }
            } while (_canvasDevice == null);
        }

        private async void Button_ClickAsync(object sender, RoutedEventArgs e)
        {
            await StartCaptureAsync();
        }

        private async void ScreenshotButton_ClickAsync(object sender, RoutedEventArgs e)
        {
            await SaveImageAsync(_screenshotFilename, _currentFrame);
        }

        private async Task SaveImageAsync(string filename, CanvasBitmap frame)
        {
            StorageFolder pictureFolder = KnownFolders.SavedPictures;

            StorageFile file = await pictureFolder.CreateFileAsync(
                filename,
                CreationCollisionOption.ReplaceExisting);

            using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await frame.SaveAsync(fileStream, CanvasBitmapFileFormat.Png, 1f);
            }
        }
    }
}
Imports System.Numerics
Imports Microsoft.Graphics.Canvas
Imports Microsoft.Graphics.Canvas.UI.Composition
Imports Windows.Graphics
Imports Windows.Graphics.Capture
Imports Windows.Graphics.DirectX
Imports Windows.UI
Imports Windows.UI.Composition
Imports Windows.UI.Xaml.Hosting

Partial Public NotInheritable Class MainPage
    Inherits Page

    ' Capture API objects.
    WithEvents CaptureItem As GraphicsCaptureItem
    WithEvents FramePool As Direct3D11CaptureFramePool

    Private _lastSize As SizeInt32
    Private _session As GraphicsCaptureSession

    ' Non-API related members.
    Private _canvasDevice As CanvasDevice
    Private _compositionGraphicsDevice As CompositionGraphicsDevice
    Private _compositor As Compositor
    Private _surface As CompositionDrawingSurface

    Sub New()
        InitializeComponent()
        Setup()
    End Sub

    Private Sub Setup()
        _canvasDevice = New CanvasDevice()
        _compositionGraphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(Window.Current.Compositor, _canvasDevice)
        _compositor = Window.Current.Compositor
        _surface = _compositionGraphicsDevice.CreateDrawingSurface(
            New Size(400, 400), DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied)
        Dim visual = _compositor.CreateSpriteVisual()
        visual.RelativeSizeAdjustment = Vector2.One
        Dim brush = _compositor.CreateSurfaceBrush(_surface)
        brush.HorizontalAlignmentRatio = 0.5F
        brush.VerticalAlignmentRatio = 0.5F
        brush.Stretch = CompositionStretch.Uniform
        visual.Brush = brush
        ElementCompositionPreview.SetElementChildVisual(Me, visual)
    End Sub

    Public Async Function StartCaptureAsync() As Task
        ' The GraphicsCapturePicker follows the same pattern the
        ' file pickers do.
        Dim picker As New GraphicsCapturePicker
        Dim item As GraphicsCaptureItem = Await picker.PickSingleItemAsync()

        ' The item may be null if the user dismissed the
        ' control without making a selection or hit Cancel.
        If item IsNot Nothing Then
            StartCaptureInternal(item)
        End If
    End Function

    Private Sub StartCaptureInternal(item As GraphicsCaptureItem)
        ' Stop the previous capture if we had one.
        StopCapture()

        CaptureItem = item
        _lastSize = CaptureItem.Size

        FramePool = Direct3D11CaptureFramePool.Create(
            _canvasDevice, ' D3D device
            DirectXPixelFormat.B8G8R8A8UIntNormalized, ' Pixel format
            2, '  Number of frames
            CaptureItem.Size) ' Size of the buffers

        _session = FramePool.CreateCaptureSession(CaptureItem)
        _session.StartCapture()
    End Sub

    Private Sub FramePool_FrameArrived(sender As Direct3D11CaptureFramePool, args As Object) Handles FramePool.FrameArrived
        ' The FrameArrived event is raised for every frame on the thread
        ' that created the Direct3D11CaptureFramePool. This means we
        ' don't have to do a null-check here, as we know we're the only
        ' one dequeueing frames in our application.  

        ' NOTE Disposing the frame retires it And returns  
        ' the buffer to the pool.

        Using frame = FramePool.TryGetNextFrame()
            ProcessFrame(frame)
        End Using
    End Sub

    Private Sub CaptureItem_Closed(sender As GraphicsCaptureItem, args As Object) Handles CaptureItem.Closed
        StopCapture()
    End Sub

    Public Sub StopCapture()
        _session?.Dispose()
        FramePool?.Dispose()
        CaptureItem = Nothing
        _session = Nothing
        FramePool = Nothing
    End Sub

    Private Sub ProcessFrame(frame As Direct3D11CaptureFrame)
        ' Resize and device-lost leverage the same function on the
        ' Direct3D11CaptureFramePool. Refactoring it this way avoids
        ' throwing in the catch block below (device creation could always
        ' fail) along with ensuring that resize completes successfully And
        ' isn't vulnerable to device-lost.

        Dim needsReset As Boolean = False
        Dim recreateDevice As Boolean = False

        If (frame.ContentSize.Width <> _lastSize.Width) OrElse
            (frame.ContentSize.Height <> _lastSize.Height) Then
            needsReset = True
            _lastSize = frame.ContentSize
        End If

        Try
            ' Take the D3D11 surface and draw it into a  
            ' Composition surface.

            ' Convert our D3D11 surface into a Win2D object.
            Dim bitmap = CanvasBitmap.CreateFromDirect3D11Surface(
                _canvasDevice,
                frame.Surface)

            ' Helper that handles the drawing for us.
            FillSurfaceWithBitmap(bitmap)
            ' This is the device-lost convention for Win2D.
        Catch e As Exception When _canvasDevice.IsDeviceLost(e.HResult)
            ' We lost our graphics device. Recreate it and reset
            ' our Direct3D11CaptureFramePool.  
            needsReset = True
            recreateDevice = True
        End Try

        If needsReset Then
            ResetFramePool(frame.ContentSize, recreateDevice)
        End If
    End Sub

    Private Sub FillSurfaceWithBitmap(canvasBitmap As CanvasBitmap)
        CanvasComposition.Resize(_surface, canvasBitmap.Size)

        Using session = CanvasComposition.CreateDrawingSession(_surface)
            session.Clear(Colors.Transparent)
            session.DrawImage(canvasBitmap)
        End Using
    End Sub

    Private Sub ResetFramePool(size As SizeInt32, recreateDevice As Boolean)
        Do
            Try
                If recreateDevice Then
                    _canvasDevice = New CanvasDevice()
                End If
                FramePool.Recreate(_canvasDevice, DirectXPixelFormat.B8G8R8A8UIntNormalized, 2, size)
                ' This is the device-lost convention for Win2D.
            Catch e As Exception When _canvasDevice.IsDeviceLost(e.HResult)
                _canvasDevice = Nothing
                recreateDevice = True
            End Try
        Loop While _canvasDevice Is Nothing
    End Sub

    Private Async Sub Button_ClickAsync(sender As Object, e As RoutedEventArgs) Handles CaptureButton.Click
        Await StartCaptureAsync()
    End Sub

End Class

비디오 녹화

애플리케이션에서 비디오를 녹화하려면, 화면 캡처 문서에 나와 있는 절차를 따라 비디오를 만들 수 있습니다. 또는 Windows.Media.AppRecording 네임스페이스사용할 수 있습니다. 데스크톱 확장 SDK의 일부이므로 Windows 데스크톱에서만 작동하며 프로젝트에서 참조를 추가해야 합니다. 확장 SDK 프로그래밍에 대한 자세한 내용은을 참조하세요.

참고하십시오

  • Windows.Graphics.Capture 네임스페이스
  • 비디오 화면 캡처