Favicon

Get screen capture of control, monitor

Peponi2/6/20252m

C#
SystemWindowsFormsDrawingControlScreen

1. Introduction

Control클래스는 DrawToBitmap() 메서드를 통해 비트맵 렌더링을 지원한다. 이를 이용해 특정 컨트롤의 클라이언트 영역을 비트맵으로 그릴 수 있다. 모니터 출력의 경우 Screen.AllScreens[]를 통해 특정 모니터 정보를 얻어올 수 있으며, Graphics.CopyFromScreen() 메서드를 통해 화면 캡쳐를 수행할 수 있다.

2. Example

ScreenCapture
using System.Drawing;
using System.Windows.Forms;
 
namespace ScreenCaptureTest;
 
public static class ScreenCapture
{
    // SaveDialog() 는 아래 확장 메서드에 기술한다.
 
    public static void Control(Control control)
    {
        Bitmap image = new Bitmap(control.Width, control.Height);
        control.DrawToBitmap(image, control.ClientRectangle);
 
        image.SaveDialog();
    }
 
    public static void Monitor(int index)
    {
        var monitorInfo = Screen.AllScreens[index].Bounds;
 
        Bitmap image = new Bitmap(monitorInfo.Width, monitorInfo.Height);
        using (Graphics g = Graphics.FromImage(image))
        {
            g.CopyFromScreen(monitorInfo.Left, monitorInfo.Top, 0, 0, monitorInfo.Size);
        }
 
        image.SaveDialog();
    }
}
BitmapExtension
public static class BitmapExtension
{
    public static void SaveDialog(this Bitmap image)
    {
        SaveFileDialog saveDialog = new SaveFileDialog
        {
            Title = "Save screenshot..",
            InitialDirectory = "C:\\",
            DefaultExt = "bmp",
            Filter = "bmp file|*.bmp;",
            OverwritePrompt = true
        };
        if (saveDialog.ShowDialog() == DialogResult.OK)
        {
            image.Save(saveDialog.FileName, System.Drawing.Imaging.ImageFormat.Bmp);
        }
    }
}

3. 참조 자료