본문 바로가기
C++ 200제/코딩 IT 정보

C# 윈폼 예제, 스크린 캡쳐 소스 (화면 ScreenShot)

by vicddory 2017. 5. 4.

C# 윈폼 예제, 스크린 캡쳐 소스 (화면 ScreenShot)


스크린 캡쳐 (ScreenShot) 프로젝트 - WindowsApplication2.zip [클릭]


C Sharp Form - Screen Shot[C# 윈폼 예제, 스크린 캡쳐 소스 (화면 ScreenShot)]


간단한 C# 윈폼 스크린샷 프로그램입니다. 필요한 건 역시, 각 좌표를 Integer 형으로 변환시켜 인식시켜 줄 네임 스페이스입니다.


1
System.Runtime.InteropServices
cs


그리고 스크린 캡쳐를 위한 좌표 계산 API를 선언합니다.


1
2
3
4
5
6
7
8
9
10
11
12
[DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
public static extern IntPtr GetDC(IntPtr hWnd);
 
[DllImport("user32.dll", ExactSpelling = true)]
public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
 
[DllImport("gdi32.dll", ExactSpelling = true)]
public static extern IntPtr BitBlt(IntPtr hDestDC, int x, int y, int nWidth,
                           int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop);
 
[DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
public static extern IntPtr GetDesktopWindow();
cs


위에 선언한 함수를 이용해 C# 윈폼 "ScreenShot" 스크린샷 생성이 가능해집니다.

다만, 전체 스크린샷이지 일부 스크린샷은 아닙니다. 프로그램 실행 후 화면 아래 Save 버튼을 누르면 아래 코드가 실행됩니다.


C# Picture Box(픽처 박스)를 이용해 현재 화면을 이미지로 저장하죠.


1
2
3
4
5
6
7
8
private void btnSave_Click(object sender, EventArgs e)
{
    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        pictureBox1.Image.Save(saveFileDialog1.FileName,
                        System.Drawing.Imaging.ImageFormat.Bmp);
    }
}
cs


코드는 간단합니다.


C# 윈폼 예제의 핵심은 아래 ScreenShot 클래스입니다. IntPtr을 이용해 윈도우 API의 DC 함수를 호출하여, 비트맵을 생성하죠. 이 클래스는 이렇게 생성된 스크린 캡쳐 이미지를 반환합니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
internal class ScreenShot
{
    public static Bitmap take()
    {
        int screenWidth = Screen.PrimaryScreen.Bounds.Width;
        int screenHeight = Screen.PrimaryScreen.Bounds.Height;
 
        Bitmap screenBmp = new Bitmap(screenWidth, screenHeight);
        Graphics g = Graphics.FromImage(screenBmp);
 
        IntPtr dc1 = API.GetDC(API.GetDesktopWindow());
        IntPtr dc2 = g.GetHdc();
 
        //Main drawing, copies the screen to the bitmap
        //last number is the copy constant
        API.BitBlt(dc2, 00, screenWidth, screenHeight, dc1, 0013369376);
 
        //Clean up
        API.ReleaseDC(API.GetDesktopWindow(), dc1);
        g.ReleaseHdc(dc2);
        g.Dispose();
 
        return screenBmp;
    }
}
cs


일단 프로그램 실행한 후 여러번 스크린 캡쳐하면서 감을 잡고, 그 뒤에 소스를 수정하여 입맛에 맞춰보세요.


C# 윈폼 예제, 스크린 캡쳐 소스 (화면 ScreenShot)

댓글