Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 10개 있습니다.)
VC++: 121. DXGI를 이용한 윈도우 화면 캡처 소스 코드(Visual C++)
; https://www.sysnet.pe.kr/2/0/11385

.NET Framework: 705. C# - SharpDX + DXGI를 이용한 윈도우 화면 캡처 소스 코드
; https://www.sysnet.pe.kr/2/0/11400

.NET Framework: 706. C# - SharpDX + DXGI를 이용한 윈도우 화면 캡처 소스 코드 + Direct2D 출력
; https://www.sysnet.pe.kr/2/0/11401

.NET Framework: 712. C# - SharpDX + DXGI를 이용한 윈도우 화면 캡처 소스 코드 + Direct2D 출력 + OpenCV
; https://www.sysnet.pe.kr/2/0/11407

.NET Framework: 713. C# - SharpDX + DXGI를 이용한 윈도우 화면 캡처 소스 코드 + Direct2D 출력 + OpenCV (2)
; https://www.sysnet.pe.kr/2/0/11408

.NET Framework: 913. C# - SharpDX + DXGI를 이용한 윈도우 화면 캡처 라이브러리
; https://www.sysnet.pe.kr/2/0/12238

.NET Framework: 1123. C# - (SharpDX + DXGI) 화면 캡처한 이미지를 빠르게 JPG로 변환하는 방법
; https://www.sysnet.pe.kr/2/0/12889

.NET Framework: 1126. C# - snagit처럼 화면 캡처를 연속으로 수행해 동영상 제작
; https://www.sysnet.pe.kr/2/0/12895

.NET Framework: 1128. C# - 화면 캡처한 이미지를 ffmpeg(FFmpeg.AutoGen)로 동영상 처리
; https://www.sysnet.pe.kr/2/0/12897

.NET Framework: 1152. C# - 화면 캡처한 이미지를 ffmpeg(FFmpeg.AutoGen)로 동영상 처리 (저해상도 현상 해결)
; https://www.sysnet.pe.kr/2/0/12963




C# - SharpDX + DXGI를 이용한 윈도우 화면 캡처 소스 코드

이전 글에서 DXGI를 이용한 화면 캡처 소스 코드를 C++로 알아봤는데요.

DXGI를 이용한 윈도우 화면 캡처 소스 코드(Visual C++)
; https://www.sysnet.pe.kr/2/0/11385

이번엔 C#으로 옮겨봤습니다. 물론 이를 위해 DirectX를 위한 Interop 라이브러리가 필요한데요, 바로 SharpDX가 그런 역할을 합니다.

A new managed .NET/C# Direct3D 11 API generated from DirectX SDK headers 
; http://code4k.blogspot.kr/2010/10/managed-netc-direct3d-11-api-generated.html

NuGet에도 배포되어 있는 데다,

SharpDX
; https://www.nuget.org/packages/SharpDX/

SharpDX.DXGI
; https://www.nuget.org/packages/SharpDX.DXGI/4.1.0-ci184

github에 소스 코드와 그 예제 코드가 모두 공개되어 있습니다. 그중에는 화면 캡처 예제도 있습니다.

SharpDX-Samples/Desktop/Direct3D11.1/ScreenCapture/Program.cs 
; https://github.com/sharpdx/SharpDX-Samples/blob/master/Desktop/Direct3D11.1/ScreenCapture/Program.cs




Nuget을 통해 SharpDX를 참조하면,

Install-Package SharpDX.Direct3D11 -Version 4.0.1 
Install-Package SharpDX.DXGI -Version 4.0.1

각각 다음의 DLL을 얻게 됩니다.

SharpDX.dll
SharpDX.DXGI.dll
SharpDX.Direct3D11.dll

이를 이용해 "DXGI를 이용한 윈도우 화면 캡처 소스 코드(Visual C++)" 글의 DXGIManager, DXGIOutputDuplication 클래스를 각각 C#으로 다음과 같이 작성할 수 있습니다.

// DXGIManager.cs

using SharpDX;
using SharpDX.DXGI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;

namespace WindowsFormsApp1
{
    public class DXGIManager : IDisposable
    {
        // ...[생략]...

        public DXGIManager(CaptureSource source)
        {
            Initialize(source);
        }

        void Initialize(CaptureSource captureSource)
        {
            _captureSource = captureSource;
            _factory = new Factory4();
            _outputs = new List<DXGIOutputDuplication>();

            int vgaCardCount = _factory.GetAdapterCount();

            foreach (Adapter adapter in _factory.Adapters)
            {
                List<Output> outputs = new List<Output>();

                foreach (Output output in adapter.Outputs)
                {
                    OutputDescription desc = output.Description;
                    if (desc.IsAttachedToDesktop == false)
                    {
                        continue;
                    }

                    outputs.Add(output);
                }

                if (outputs.Count == 0)
                {
                    continue;
                }

                SharpDX.Direct3D11.Device device = new SharpDX.Direct3D11.Device(adapter);

                foreach (Output output in outputs)
                {
                    using (Output1 output1 = output.QueryInterface<Output1>())
                    {
                        OutputDuplication outputDuplication = output1.DuplicateOutput(device);

                        if (outputDuplication == null)
                        {
                            continue;
                        }

                        _outputs.Add(
                            new DXGIOutputDuplication(adapter, device, outputDuplication, output1.Description));
                    }
                }
                // ...[생략]...
            }

            if (this.Initialized == true)
            {
                CalcOutputRect();
            }
        }

        public bool Capture(byte[] buf, int timeout)
        {
            foreach (DXGIOutputDuplication dupOutput in GetOutputDuplicationByCaptureSource())
            {
                Rectangle desktopBounds = dupOutput.DesktopCoordinates;
                if (dupOutput.AcquireNextFrame(timeout, copyBuffer, buf) == false)
                {
                    return false;
                }
            }

            return true;
        }

        private void copyBuffer(Surface1 surface1, Rectangle desktopBounds, byte[] buf)
        {
            if (surface1 == null)
            {
                return;
            }

            DataRectangle map = surface1.Map(MapFlags.Read);

            GCHandle pinnedArray = GCHandle.Alloc(buf, GCHandleType.Pinned);
            IntPtr dstPtr = pinnedArray.AddrOfPinnedObject();
            IntPtr srcPtr = map.DataPointer;

            int height = desktopBounds.Height;
            int width = desktopBounds.Width;

            Rectangle offsetBounds = desktopBounds;
            offsetBounds.Offset(-this._outputRect.Left, -this._outputRect.Top);

            {
                for (int y = 0; y < height; y++)
                {
                    Utilities.CopyMemory(dstPtr + (offsetBounds.Left) * 4, srcPtr, width * 4);

                    srcPtr = IntPtr.Add(srcPtr, map.Pitch);
                    dstPtr = IntPtr.Add(dstPtr, this.Width * 4);
                }
            }

            pinnedArray.Free();
            surface1.Unmap();
        }

        // ...[생략]...

        private List<DXGIOutputDuplication> GetOutputDuplicationByCaptureSource()
        {
            List<DXGIOutputDuplication> list = new List<DXGIOutputDuplication>();
            int nthMonitor = 0;

            foreach (DXGIOutputDuplication output in _outputs)
            {
                switch (_captureSource)
                {
                    case CaptureSource.Monitor1:
                        if (output.IsPrimary() == true)
                        {
                            list.Add(output);
                        }
                        break;

                    case CaptureSource.Monitor2:
                        if (output.IsPrimary() == false)
                        {
                            list.Add(output);
                        }
                        break;

                    case CaptureSource.Monitor3:
                        if (output.IsPrimary() == false)
                        {
                            nthMonitor++;
                        }

                        if (nthMonitor == ((int)CaptureSource.Monitor3) - 1)
                        {
                            list.Add(output);
                        }
                        break;

                    case CaptureSource.Desktop:
                        list.Add(output);
                        break;
                }

                if (_captureSource != CaptureSource.Desktop && list.Count == 1)
                {
                    break;
                }
            }

            return list;
        }

        // ...[생략]...
    }
}

// DXGIManager.cs

using SharpDX;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using SharpDX.Mathematics.Interop;
using System;
using System.Drawing;
using System.Runtime.InteropServices;

namespace WindowsFormsApp1
{
    class DXGIOutputDuplication
    {
        Adapter _adapter;
        SharpDX.Direct3D11.Device _device;
        SharpDX.Direct3D11.DeviceContext _deviceContext;
        OutputDuplication _outputDuplication;
        OutputDescription _description;

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern bool GetMonitorInfo(IntPtr hMonitor, ref MonitorInfoEx lpmi);

        public DXGIOutputDuplication(Adapter adapter,
            SharpDX.Direct3D11.Device device,
            OutputDuplication outputDuplication, OutputDescription description)
        {
            _adapter = adapter;

            _device = device;
            _deviceContext = _device.ImmediateContext;

            _outputDuplication = outputDuplication;

            _description = description;
        }

        // ...[생략]...

        internal bool AcquireNextFrame(int timeout, Action copyAction, byte[] buf)
        {
            OutputDuplicateFrameInformation fi;
            SharpDX.DXGI.Resource desktopResource = null;

            try
            {
                _outputDuplication.AcquireNextFrame(timeout, out fi, out desktopResource);
            }
            catch (SharpDXException e)
            {
                if (e.ResultCode == DXGIError.DXGI_ERROR_ACCESS_LOST)
                {
                    throw;
                }

                return false;
            }

            if (desktopResource == null)
            {
                return false;
            }

            try
            {
                using (Texture2D textureResource = desktopResource.QueryInterface())
                {
                    Texture2DDescription desc = textureResource.Description;

                    Texture2DDescription textureDescription = desc;
                    textureDescription.MipLevels = 1;
                    textureDescription.ArraySize = 1;
                    textureDescription.SampleDescription.Count = 1;
                    textureDescription.SampleDescription.Quality = 0;
                    textureDescription.Usage = ResourceUsage.Staging;
                    textureDescription.BindFlags = 0;
                    textureDescription.CpuAccessFlags = CpuAccessFlags.Read;
                    textureDescription.OptionFlags = ResourceOptionFlags.None;

                    using (Texture2D d3d11Texture2D = new Texture2D(_device, textureDescription))
                    {
                        _device.ImmediateContext.CopyResource(textureResource, d3d11Texture2D);

                        using (Surface1 surface = d3d11Texture2D.QueryInterface())
                        {
                            copyAction(surface, this.DesktopCoordinates, buf);
                            return true;
                        }
                    }
                }
            }
            finally
            {
                if (desktopResource != null)
                {
                    desktopResource.Dispose();
                }

                _outputDuplication.ReleaseFrame();
            }
        }

        // ...[생략]...
    }
}

첨부한 파일은 위의 예제 코드를 모두 포함, 동작하는 프로젝트입니다. 실행하면 윈도우가 하나 뜨는데, 그 윈도우에 포커스를 두고 Ctrl + C키를 누르면 1번 모니터의 화면을 캡처해서 윈도우에 출력합니다. 이렇게!

dxgi_capture_1.png




참고로, 그래픽 카드 제조사 측에서 제공하는 화면 캡처 SDK도 있습니다. (언어는 C++입니다.)

NVIDIA Capture SDK
; https://developer.nvidia.com/capture-sdk

[PDF] NVIDIA CAPTURE SDK PROGRAMMING GUIDE
; http://developer.download.nvidia.com/designworks/capture-sdk/docs/6.1/NVIDIA-Capture-SDK-Programming-Guide.pdf




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 12/14/2017]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2019-12-04 04시05분
[ffdfdsf] 캡쳐시마다 계속 dx초기화하고 변수만들고 초기화시키고 하는건가요?? 속도가 느린것같은데 어떻게하나요..
그리고 다출력했으면 사용한 메모리 릴리즈 해야되는데 어떤거어떤거 해야되나요
[guest]
2019-12-04 08시30분
제가 공유한 소스 코드에서 캡처 시마다 계속 dx를 초기화했나요?
정성태
2019-12-04 11시15분
[ffdfdsf] _captureEvent.Set(); 이것만 타이머에넣고 돌렸습니다.
[guest]
2021-04-16 11시22분
ShareX/ShareX - a free and open source program that lets you capture or record any area of your screen and share it with a single press of a key.
; https://github.com/ShareX/ShareX
정성태
2023-03-14 09시20분
[초보입니다.] 뭔가 궁금한게 생겨서 검색하다보면 여기로 연결됩니다
항상 좋은 자료들에 감사드립니다.
첨부파일로 그대로 캡처를 연속으로 해보면 메모리가 지속적으로 늘어나는데 초보라서 어느부분을 고쳐야할지 몰라서 문의드립니다.
[guest]
2023-03-14 09시40분
얼핏 기억에 ^^ 그랬던 적이 있었지만 아마 그 이후에 수정했을 것입니다. 다음의 글에 등록한 github 소스 코드가 최신이니 그걸 받아서 해보세요.

C# - SharpDX + DXGI를 이용한 윈도우 화면 캡처 라이브러리
; https://www.sysnet.pe.kr/2/0/12238
정성태
2023-03-15 01시17분
[초보입니다.] 빠른 답변에 감사드립니다.
깃허브에 있는걸로 하니 메모리 누수가 없습니다.
감사합니다.
[guest]
2023-03-15 01시45분
[초보입니다] 깃허브에 있는코드는 directxView 에 출력후 bitmap파일로 저장하게 되어있던데 directxView 에 출력없이 바로 bitmap를 반환받으려면 어느곳을 수정해야 할지 시간되실때 알려주시면 감사하겠습니다.
처음 접하는 부분이라 모르는게 너무많아 죄송합니다.
[guest]
2023-07-28 01시37분
정성태

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13600정성태4/18/2024215닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024259닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024274닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드1
13597정성태4/15/2024338닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024667닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024789닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/2024989닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241045닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241202C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241164닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241071Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241138닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241191닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241149오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241292Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241092Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241046개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241149Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241222Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241585개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241136닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241493오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241627닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241864닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241543닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...