티스토리 뷰

Visual Studio 2012사용


특정 프로세스의 윈도우 화면을 캡쳐해보자.

윈폼 프로그램에서 버튼 클릭으로 메모장의 화면을 캡쳐하는 것이 목표


1. 우선 Windows Form 응용프로그램으로 프로젝트 생성하자.

- 버튼 컨트롤 하나 생성


2. using 문 추가

using System.Runtime.InteropServices;        //DllImport를 사용하기 위해

using System.Drawing.Imaging;                 //Bitmap 자원 활용


3. 소스는 아래와 같이 작성


namespace Capture
{
  public partial class Form1 : Form
  {
    [StructLayout(LayoutKind.Sequential)]
    public struct Rect
    {
      public int left;
      public int top;
      public int right;
      public int bottom;
    }

    [DllImport("user32.dll")]
    private static extern int SetForegroundWindow(IntPtr hWnd);

    private const int SW_RESTORE = 9;

    [DllImport("user32.dll")]
    private static extern IntPtr ShowWindow(IntPtr hWnd, int nCmdShow);

    [DllImport("user32.dll")]
    public static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);

    public Bitmap CaptureApplication(string procName)
    {
      Process proc;

      // Cater for cases when the process can't be located.
      try
      {
        proc = Process.GetProcessesByName(procName)[0];
      }
      catch (IndexOutOfRangeException e)
      {
        return null;
      }

      // You need to focus on the application
      SetForegroundWindow(proc.MainWindowHandle);
      ShowWindow(proc.MainWindowHandle, SW_RESTORE);

      // You need some amount of delay, but 1 second may be overkill
      Thread.Sleep(1000);

      Rect rect = new Rect();
      IntPtr error = GetWindowRect(proc.MainWindowHandle, ref rect);

      // sometimes it gives error.
      while (error == (IntPtr)0)
      {
        error = GetWindowRect(proc.MainWindowHandle, ref rect);
      }

      int width = rect.right - rect.left;
      int height = rect.bottom - rect.top;

      Bitmap bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
      Graphics.FromImage(bmp).CopyFromScreen(rect.left,
                                             rect.top,
                                             0,
                                             0,
                                             new Size(width, height),
                                             CopyPixelOperation.SourceCopy);
      return bmp;
    }

    public Form1()
    {
      InitializeComponent();
    }

    private void btn1_Click(object sender, EventArgs e)
    {
      Bitmap bmpTmp;
      bmpTmp = CaptureApplication("notepad");

      bmpTmp.Save("d:\\test.png", ImageFormat.Png);
    }
  }
}

- btn1 버튼 클릭시 메모장 프로세스 이름을 읽어서 화면을 캡쳐한다.

- 캡쳐한 내용을 D:\test.png로 저장한다.


- 끝







댓글