调用API捕获屏幕图像

捕获屏幕图像俗称抓屏,在http://cnblogs.com/spidertan/archive/2004/09/03/39362.aspx提供了C#的版本,本文提供VB.NET和C#两个语言版本的代码(ScreenCapture.VB和ScreenCapture.CS),主要功能就是捕获屏幕或者窗口上的图象。

http://www.codeguru.com/code/legacy/cs_graphics/CaptureScreenDemo.zip提供了完整的工程代码,但跟本文没有关系,仅仅提供下载资源。

用ScreenCapture这个类特别简单,该类有四个方法:

  • public Image CaptureScreen() 捕获整个屏幕的图象
  • public Image CaptureWindow(IntPtr handle) 捕获窗口上的图象
  • public void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format) 捕获窗口图像并且保存为一个文件
  • public void CaptureScreenToFile(string filename, ImageFormat format) 捕获整个屏幕的图像并且保存为一个文件

示例与快速入门

VB.NET

Dim sc As New ScreenCapture()
' 捕获整个屏幕的图象
Dim img As Image = sc.CaptureScreen()
' 在ID为imageDisplay的Picture控件显示图像
Me.imageDisplay.Image = img
' 捕获窗口图像并且保存为一个文件
sc.CaptureWindowToFile(Me.Handle, "C: emp2.gif", ImageFormat.Gif)

C#

ScreenCapture sc = new ScreenCapture();
// 捕获整个屏幕的图象
Image img = sc.CaptureScreen();
// 在ID为imageDisplay的Picture控件显示图像
this.imageDisplay.Image = img;
// 捕获窗口图像并且保存为一个文件
sc.CaptureWindowToFile(this.Handle,"C:\temp2.gif",ImageFormat.Gif);

ScreenCapture类的代码

VB.NET

Imports System
Imports System.Runtime.InteropServices
Imports System.Drawing
Imports System.Drawing.Imaging

Namespace ScreenShotDemoNamespace ScreenShotDemo
    _
   '/ <summary>
   '/ Provides functions to capture the entire screen, or a particular window, and save it to a file.
   '/ </summary>
   Public Class ScreenCaptureClass ScreenCapture

      '/ <summary>
      '/ Creates an Image object containing a screen shot of the entire desktop
      '/ </summary>
      '/ <returns></returns>
      Public Function CaptureScreen()Function CaptureScreen() As Image
         Return CaptureWindow(User32.GetDesktopWindow())
      End Function 'CaptureScreen

      '/ <summary>
      '/ Creates an Image object containing a screen shot of a specific window
      '/ </summary>
      '/ <param name="handle">The handle to the window. (In windows forms, this is obtained by the Handle property)</param>
      '/ <returns></returns>
      Public Function CaptureWindow()Function CaptureWindow(handle As IntPtr) As Image
         ' get te hDC of the target window
         Dim hdcSrc As IntPtr = User32.GetWindowDC(handle)
         ' get the size
         Dim windowRect As New User32.RECT()
         User32.GetWindowRect(handle, windowRect)
         Dim width As Integer = windowRect.right - windowRect.left
         Dim height As Integer = windowRect.bottom - windowRect.top
         ' create a device context we can copy to
         Dim hdcDest As IntPtr = GDI32.CreateCompatibleDC(hdcSrc)
         ' create a bitmap we can copy it to,
         ' using GetDeviceCaps to get the width/height
         Dim hBitmap As IntPtr = GDI32.CreateCompatibleBitmap(hdcSrc, width, height)
         ' select the bitmap object
         Dim hOld As IntPtr = GDI32.SelectObject(hdcDest, hBitmap)
         ' bitblt over
         GDI32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, GDI32.SRCCOPY)
         ' restore selection
         GDI32.SelectObject(hdcDest, hOld)
         ' clean up 
         GDI32.DeleteDC(hdcDest)
         User32.ReleaseDC(handle, hdcSrc)
         
         ' get a .NET image object for it
         Dim img As Image = Image.FromHbitmap(hBitmap)
         ' free up the Bitmap object
         GDI32.DeleteObject(hBitmap)
         
         Return img
      End Function 'CaptureWindow

      '/ <summary>
      '/ Captures a screen shot of a specific window, and saves it to a file
      '/ </summary>
      '/ <param name="handle"></param>
      '/ <param name="filename"></param>
      '/ <param name="format"></param>
      Public Sub CaptureWindowToFile()Sub CaptureWindowToFile(handle As IntPtr, filename As String, format As ImageFormat)
         Dim img As Image = CaptureWindow(handle)
         img.Save(filename, format)
      End Sub 'CaptureWindowToFile

      '/ <summary>
      '/ Captures a screen shot of the entire desktop, and saves it to a file
      '/ </summary>
      '/ <param name="filename"></param>
      '/ <param name="format"></param>
      Public Sub CaptureScreenToFile()Sub CaptureScreenToFile(filename As String, format As ImageFormat)
         Dim img As Image = CaptureScreen()
         img.Save(filename, format)
      End Sub 'CaptureScreenToFile
       _
      
      '/ <summary>
      '/ Helper class containing Gdi32 API functions
      '/ </summary>
      Private Class GDI32Class GDI32
         
         Public SRCCOPY As Integer = &HCC0020
          ' BitBlt dwRop parameter
         Public Shared<DllImport("gdi32.dll")>  _
         Function BitBlt()Function BitBlt(hObject As IntPtr, nXDest As Integer, nYDest As Integer, nWidth As Integer, nHeight As Integer, hObjectSource As IntPtr, nXSrc As Integer, nYSrc As Integer, dwRop As Integer) As Boolean
         
         Public Shared<DllImport("gdi32.dll")>  _
         Function CreateCompatibleBitmap()Function CreateCompatibleBitmap(hDC As IntPtr, nWidth As Integer, nHeight As Integer) As IntPtr
         
         Public Shared<DllImport("gdi32.dll")>  _
         Function CreateCompatibleDC()Function CreateCompatibleDC(hDC As IntPtr) As IntPtr
         
         Public Shared<DllImport("gdi32.dll")>  _
         Function DeleteDC()Function DeleteDC(hDC As IntPtr) As Boolean
         
         Public Shared<DllImport("gdi32.dll")>  _
         Function DeleteObject()Function DeleteObject(hObject As IntPtr) As Boolean
         
         Public Shared<DllImport("gdi32.dll")>  _
         Function SelectObject()Function SelectObject(hDC As IntPtr, hObject As IntPtr) As IntPtr
      End Class 'GDI32
       _
      
      '/ <summary>
      '/ Helper class containing User32 API functions
      '/ </summary>
      Private Class User32Class User32
         <StructLayout(LayoutKind.Sequential)>  _
         Public Structure RECTStructure RECT
            Public left As Integer
            Public top As Integer
            Public right As Integer
            Public bottom As Integer
         End Structure 'RECT
         
         Public Shared<DllImport("user32.dll")>  _
         Function GetDesktopWindow()Function GetDesktopWindow() As IntPtr
         
         Public Shared<DllImport("user32.dll")>  _
         Function GetWindowDC()Function GetWindowDC(hWnd As IntPtr) As IntPtr
         
         Public Shared<DllImport("user32.dll")>  _
         Function ReleaseDC()Function ReleaseDC(hWnd As IntPtr, hDC As IntPtr) As IntPtr
         
         Public Shared<DllImport("user32.dll")>  _
         Function GetWindowRect()Function GetWindowRect(hWnd As IntPtr, ByRef rect As RECT) As IntPtr
      End Class 'User32
   End Class 'ScreenCapture
End Namespace 'ScreenShotDemo

C#

using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;

namespace ScreenShotDemo
{
    /// <summary>
    /// Provides functions to capture the entire screen, or a particular window, and save it to a file.
    /// </summary>
    public class ScreenCapture
    {
        /// <summary>
        /// Creates an Image object containing a screen shot of the entire desktop
        /// </summary>
        /// <returns></returns>
        public Image CaptureScreen()
        {
            return CaptureWindow( User32.GetDesktopWindow() );
        }

        /// <summary>
        /// Creates an Image object containing a screen shot of a specific window
        /// </summary>
        /// <param name="handle">The handle to the window. (In windows forms, this is obtained by the Handle property)</param>
        /// <returns></returns>
        public Image CaptureWindow(IntPtr handle)
        {
            // get te hDC of the target window
            IntPtr hdcSrc = User32.GetWindowDC(handle);
            // get the size
            User32.RECT windowRect = new User32.RECT();
            User32.GetWindowRect(handle,ref windowRect);
            int width = windowRect.right - windowRect.left;
            int height = windowRect.bottom - windowRect.top;
            // create a device context we can copy to
            IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
            // create a bitmap we can copy it to,
            // using GetDeviceCaps to get the width/height
            IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc,width,height); 
            // select the bitmap object
            IntPtr hOld = GDI32.SelectObject(hdcDest,hBitmap);
            // bitblt over
            GDI32.BitBlt(hdcDest,0,0,width,height,hdcSrc,0,0,GDI32.SRCCOPY);
            // restore selection
            GDI32.SelectObject(hdcDest,hOld);
            // clean up 
            GDI32.DeleteDC(hdcDest);
            User32.ReleaseDC(handle,hdcSrc);

            // get a .NET image object for it
            Image img = Image.FromHbitmap(hBitmap);
            // free up the Bitmap object
            GDI32.DeleteObject(hBitmap);

            return img;
        }

        /// <summary>
        /// Captures a screen shot of a specific window, and saves it to a file
        /// </summary>
        /// <param name="handle"></param>
        /// <param name="filename"></param>
        /// <param name="format"></param>
        public void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format) 
        {
            Image img = CaptureWindow(handle);
            img.Save(filename,format);
        }

        /// <summary>
        /// Captures a screen shot of the entire desktop, and saves it to a file
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="format"></param>
        public void CaptureScreenToFile(string filename, ImageFormat format) 
        {
            Image img = CaptureScreen();
            img.Save(filename,format);
        }
       
        /// <summary>
        /// Helper class containing Gdi32 API functions
        /// </summary>
        private class GDI32
        {            
            public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter

            [DllImport("gdi32.dll")]
            public static extern bool BitBlt(IntPtr hObject,int nXDest,int nYDest,
                int nWidth,int nHeight,IntPtr hObjectSource,
                int nXSrc,int nYSrc,int dwRop);
            [DllImport("gdi32.dll")]
            public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC,int nWidth, int nHeight);
            [DllImport("gdi32.dll")]
            public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
            [DllImport("gdi32.dll")]
            public static extern bool DeleteDC(IntPtr hDC);
            [DllImport("gdi32.dll")]
            public static extern bool DeleteObject(IntPtr hObject);
            [DllImport("gdi32.dll")]
            public static extern IntPtr SelectObject(IntPtr hDC,IntPtr hObject);
        }
 
        /// <summary>
        /// Helper class containing User32 API functions
        /// </summary>
        private class User32
        {
            [StructLayout(LayoutKind.Sequential)]
            public struct RECT
            {
                public int left;
                public int top;
                public int right;
                public int bottom;
            }

            [DllImport("user32.dll")]
            public static extern IntPtr GetDesktopWindow();
            [DllImport("user32.dll")]
            public static extern IntPtr GetWindowDC(IntPtr hWnd);
            [DllImport("user32.dll")]
            public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDC);
            [DllImport("user32.dll")]
            public static extern IntPtr GetWindowRect(IntPtr hWnd,ref RECT rect);
        }
    }
}

posted on 2004-09-25 10:53 小牛哥 阅读(85) 评论(1)



2004-09-26 03:17 | zealic

太麻烦了,抓窗口只需要两个API

public static Image GetFormScreen(IntPtr hwnd)
{
    Control n_Form = (Control)Control.FromHandle(hwnd);
    Image n_Serceen = new Bitmap(n_Form.Width, n_Form.Height);

    Graphics ImgGrp = Graphics.FromImage(n_Serceen);
    IntPtr Hdc = ImgGrp.GetHdc();
    IntPtr scrDC = Library.User32.GetWindowDC(hwnd);
    Gdi32.BitBlt(Hdc, 0, 0, n_Form.Width, n_Form.Height, scrDC, 0, 0, SRCCOPY);
    ImgGrp.ReleaseHdc(Hdc);
    return n_Serceen;
}

抓屏幕只需要3个

public static Image PrintScreen(int X, int Y,int Width, int Height)
{
    Image n_Serceen = new Bitmap(Width, Height);

    Graphics ImgGrp = Graphics.FromImage(n_Serceen);
    IntPtr Hdc = ImgGrp.GetHdc();
    IntPtr scrDC = User32.GetWindowDC(User32.GetDesktopWindow());
    Gdi32.BitBlt(Hdc, 0, 0, Width, Height, scrDC, 0, 0, Enum.PatBlt.SRCCOPY);
    ImgGrp.ReleaseHdc(Hdc);
    return n_Serceen;
}
Contributors: FHL