调用API捕获屏幕图像

本文提供了VB.NET和C#两个语言版本的代码(ScreenCapture.VB和ScreenCapture.CS),用于捕获屏幕或窗口上的图象。介绍了ScreenCapture类的四个方法,包括捕获整个屏幕或窗口图象、保存为文件等,还给出了示例与快速入门。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

捕获屏幕图像俗称抓屏,在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

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

C#

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

ScreenCapture类的代码
VB.NET

None.gif Imports  System
None.gif
Imports  System.Runtime.InteropServices
None.gif
Imports  System.Drawing
None.gif
Imports  System.Drawing.Imaging
None.gif
None.gif
ExpandedBlockStart.gifContractedBlock.gif
Namespace ScreenShotDemo Namespace ScreenShotDemo
InBlock.gif    _
InBlock.gif   
'/ <summary>
InBlock.gif
   '/ Provides functions to capture the entire screen, or a particular window, and save it to a file.
InBlock.gif
   '/ </summary>
ExpandedSubBlockStart.gifContractedSubBlock.gif
   Public Class ScreenCaptureClass ScreenCapture
InBlock.gif      
InBlock.gif      
'/ <summary>
InBlock.gif
      '/ Creates an Image object containing a screen shot of the entire desktop
InBlock.gif
      '/ </summary>
InBlock.gif
      '/ <returns></returns>
ExpandedSubBlockStart.gifContractedSubBlock.gif
      Public Function CaptureScreen()Function CaptureScreen() As Image
InBlock.gif         
Return CaptureWindow(User32.GetDesktopWindow())
ExpandedSubBlockEnd.gif      
End Function
 'CaptureScreen
InBlock.gif
      
InBlock.gif      
InBlock.gif      
'/ <summary>
InBlock.gif
      '/ Creates an Image object containing a screen shot of a specific window
InBlock.gif
      '/ </summary>
InBlock.gif
      '/ <param name="handle">The handle to the window. (In windows forms, this is obtained by the Handle property)</param>
InBlock.gif
      '/ <returns></returns>
ExpandedSubBlockStart.gifContractedSubBlock.gif
      Public Function CaptureWindow()Function CaptureWindow(handle As IntPtr) As Image
InBlock.gif         
' get te hDC of the target window
InBlock.gif
         Dim hdcSrc As IntPtr = User32.GetWindowDC(handle)
InBlock.gif         
' get the size
InBlock.gif
         Dim windowRect As New User32.RECT()
InBlock.gif         User32.GetWindowRect(handle, windowRect)
InBlock.gif         
Dim width As Integer = windowRect.right - windowRect.left
InBlock.gif         
Dim height As Integer = windowRect.bottom - windowRect.top
InBlock.gif         
' create a device context we can copy to
InBlock.gif
         Dim hdcDest As IntPtr = GDI32.CreateCompatibleDC(hdcSrc)
InBlock.gif         
' create a bitmap we can copy it to,
InBlock.gif
         ' using GetDeviceCaps to get the width/height
InBlock.gif
         Dim hBitmap As IntPtr = GDI32.CreateCompatibleBitmap(hdcSrc, width, height)
InBlock.gif         
' select the bitmap object
InBlock.gif
         Dim hOld As IntPtr = GDI32.SelectObject(hdcDest, hBitmap)
InBlock.gif         
' bitblt over
InBlock.gif
         GDI32.BitBlt(hdcDest, 00, width, height, hdcSrc, 00, GDI32.SRCCOPY)
InBlock.gif         
' restore selection
InBlock.gif
         GDI32.SelectObject(hdcDest, hOld)
InBlock.gif         
' clean up 
InBlock.gif
         GDI32.DeleteDC(hdcDest)
InBlock.gif         User32.ReleaseDC(handle, hdcSrc)
InBlock.gif         
InBlock.gif         
' get a .NET image object for it
InBlock.gif
         Dim img As Image = Image.FromHbitmap(hBitmap)
InBlock.gif         
' free up the Bitmap object
InBlock.gif
         GDI32.DeleteObject(hBitmap)
InBlock.gif         
InBlock.gif         
Return img
ExpandedSubBlockEnd.gif      
End Function
 'CaptureWindow
InBlock.gif
      
InBlock.gif      
InBlock.gif      
'/ <summary>
InBlock.gif
      '/ Captures a screen shot of a specific window, and saves it to a file
InBlock.gif
      '/ </summary>
InBlock.gif
      '/ <param name="handle"></param>
InBlock.gif
      '/ <param name="filename"></param>
InBlock.gif
      '/ <param name="format"></param>
ExpandedSubBlockStart.gifContractedSubBlock.gif
      Public Sub CaptureWindowToFile()Sub CaptureWindowToFile(handle As IntPtr, filename As Stringformat As ImageFormat)
InBlock.gif         
Dim img As Image = CaptureWindow(handle)
InBlock.gif         img.Save(filename, 
format)
ExpandedSubBlockEnd.gif      
End Sub
 'CaptureWindowToFile
InBlock.gif
      
InBlock.gif      
InBlock.gif      
'/ <summary>
InBlock.gif
      '/ Captures a screen shot of the entire desktop, and saves it to a file
InBlock.gif
      '/ </summary>
InBlock.gif
      '/ <param name="filename"></param>
InBlock.gif
      '/ <param name="format"></param>
ExpandedSubBlockStart.gifContractedSubBlock.gif
      Public Sub CaptureScreenToFile()Sub CaptureScreenToFile(filename As Stringformat As ImageFormat)
InBlock.gif         
Dim img As Image = CaptureScreen()
InBlock.gif         img.Save(filename, 
format)
ExpandedSubBlockEnd.gif      
End Sub
 'CaptureScreenToFile
InBlock.gif
       _
InBlock.gif      
InBlock.gif      
'/ <summary>
InBlock.gif
      '/ Helper class containing Gdi32 API functions
InBlock.gif
      '/ </summary>
ExpandedSubBlockStart.gifContractedSubBlock.gif
      Private Class GDI32Class GDI32
InBlock.gif         
InBlock.gif         
Public SRCCOPY As Integer = &HCC0020
InBlock.gif          
' BitBlt dwRop parameter
InBlock.gif
         Public Shared<DllImport("gdi32.dll")>  _
ExpandedSubBlockStart.gifContractedSubBlock.gif         
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 IntegerAs Boolean
InBlock.gif         
InBlock.gif         
Public Shared<DllImport("gdi32.dll")>  _
ExpandedSubBlockStart.gifContractedSubBlock.gif         
Function CreateCompatibleBitmap()Function CreateCompatibleBitmap(hDC As IntPtr, nWidth As Integer, nHeight As IntegerAs IntPtr
InBlock.gif         
InBlock.gif         
Public Shared<DllImport("gdi32.dll")>  _
ExpandedSubBlockStart.gifContractedSubBlock.gif         
Function CreateCompatibleDC()Function CreateCompatibleDC(hDC As IntPtr) As IntPtr
InBlock.gif         
InBlock.gif         
Public Shared<DllImport("gdi32.dll")>  _
ExpandedSubBlockStart.gifContractedSubBlock.gif         
Function DeleteDC()Function DeleteDC(hDC As IntPtr) As Boolean
InBlock.gif         
InBlock.gif         
Public Shared<DllImport("gdi32.dll")>  _
ExpandedSubBlockStart.gifContractedSubBlock.gif         
Function DeleteObject()Function DeleteObject(hObject As IntPtr) As Boolean
InBlock.gif         
InBlock.gif         
Public Shared<DllImport("gdi32.dll")>  _
ExpandedSubBlockStart.gifContractedSubBlock.gif         
Function SelectObject()Function SelectObject(hDC As IntPtr, hObject As IntPtr) As IntPtr
ExpandedSubBlockEnd.gif      
End Class
 'GDI32
InBlock.gif
       _
InBlock.gif      
InBlock.gif      
'/ <summary>
InBlock.gif
      '/ Helper class containing User32 API functions
InBlock.gif
      '/ </summary>
ExpandedSubBlockStart.gifContractedSubBlock.gif
      Private Class User32Class User32
InBlock.gif         
<StructLayout(LayoutKind.Sequential)>  _
ExpandedSubBlockStart.gifContractedSubBlock.gif         
Public Structure RECTStructure RECT
InBlock.gif            
Public left As Integer
InBlock.gif            
Public top As Integer
InBlock.gif            
Public right As Integer
InBlock.gif            
Public bottom As Integer
ExpandedSubBlockEnd.gif         
End Structure
 'RECT
InBlock.gif
         
InBlock.gif         
InBlock.gif         
Public Shared<DllImport("user32.dll")>  _
ExpandedSubBlockStart.gifContractedSubBlock.gif         
Function GetDesktopWindow()Function GetDesktopWindow() As IntPtr
InBlock.gif         
InBlock.gif         
Public Shared<DllImport("user32.dll")>  _
ExpandedSubBlockStart.gifContractedSubBlock.gif         
Function GetWindowDC()Function GetWindowDC(hWnd As IntPtr) As IntPtr
InBlock.gif         
InBlock.gif         
Public Shared<DllImport("user32.dll")>  _
ExpandedSubBlockStart.gifContractedSubBlock.gif         
Function ReleaseDC()Function ReleaseDC(hWnd As IntPtr, hDC As IntPtr) As IntPtr
InBlock.gif         
InBlock.gif         
Public Shared<DllImport("user32.dll")>  _
ExpandedSubBlockStart.gifContractedSubBlock.gif         
Function GetWindowRect()Function GetWindowRect(hWnd As IntPtr, ByRef rect As RECT) As IntPtr
ExpandedSubBlockEnd.gif      
End Class
 'User32
ExpandedSubBlockEnd.gif
   End Class
 'ScreenCapture 
ExpandedBlockEnd.gif
End Namespace
  ' ScreenShotDemo
None.gif

C#

None.gif using  System;
None.gif
using  System.Runtime.InteropServices;
None.gif
using  System.Drawing;
None.gif
using  System.Drawing.Imaging;
None.gif
None.gif
namespace  ScreenShotDemo
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// Provides functions to capture the entire screen, or a particular window, and save it to a file.
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public class ScreenCapture
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Creates an Image object containing a screen shot of the entire desktop
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <returns></returns>

InBlock.gif        public Image CaptureScreen() 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return CaptureWindow( User32.GetDesktopWindow() );
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Creates an Image object containing a screen shot of a specific window
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="handle">The handle to the window. (In windows forms, this is obtained by the Handle property)</param>
ExpandedSubBlockEnd.gif        
/// <returns></returns>

InBlock.gif        public Image CaptureWindow(IntPtr handle)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
// get te hDC of the target window
InBlock.gif
            IntPtr hdcSrc = User32.GetWindowDC(handle);
InBlock.gif            
// get the size
InBlock.gif
            User32.RECT windowRect = new User32.RECT();
InBlock.gif            User32.GetWindowRect(handle,
ref windowRect);
InBlock.gif            
int width = windowRect.right - windowRect.left;
InBlock.gif            
int height = windowRect.bottom - windowRect.top;
InBlock.gif            
// create a device context we can copy to
InBlock.gif
            IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
InBlock.gif            
// create a bitmap we can copy it to,
InBlock.gif            
// using GetDeviceCaps to get the width/height
InBlock.gif
            IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc,width,height); 
InBlock.gif            
// select the bitmap object
InBlock.gif
            IntPtr hOld = GDI32.SelectObject(hdcDest,hBitmap);
InBlock.gif            
// bitblt over
InBlock.gif
            GDI32.BitBlt(hdcDest,0,0,width,height,hdcSrc,0,0,GDI32.SRCCOPY);
InBlock.gif            
// restore selection
InBlock.gif
            GDI32.SelectObject(hdcDest,hOld);
InBlock.gif            
// clean up 
InBlock.gif
            GDI32.DeleteDC(hdcDest);
InBlock.gif            User32.ReleaseDC(handle,hdcSrc);
InBlock.gif
InBlock.gif            
// get a .NET image object for it
InBlock.gif
            Image img = Image.FromHbitmap(hBitmap);
InBlock.gif            
// free up the Bitmap object
InBlock.gif
            GDI32.DeleteObject(hBitmap);
InBlock.gif
InBlock.gif            
return img;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Captures a screen shot of a specific window, and saves it to a file
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="handle"></param>
InBlock.gif        
/// <param name="filename"></param>
ExpandedSubBlockEnd.gif        
/// <param name="format"></param>

InBlock.gif        public void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format) 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Image img 
= CaptureWindow(handle);
InBlock.gif            img.Save(filename,format);
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Captures a screen shot of the entire desktop, and saves it to a file
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="filename"></param>
ExpandedSubBlockEnd.gif        
/// <param name="format"></param>

InBlock.gif        public void CaptureScreenToFile(string filename, ImageFormat format) 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Image img 
= CaptureScreen();
InBlock.gif            img.Save(filename,format);
ExpandedSubBlockEnd.gif        }

InBlock.gif       
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Helper class containing Gdi32 API functions
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        private class GDI32
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
InBlock.gif            
public const int SRCCOPY = 0x00CC0020// BitBlt dwRop parameter
InBlock.gif

InBlock.gif            [DllImport(
"gdi32.dll")]
InBlock.gif            
public static extern bool BitBlt(IntPtr hObject,int nXDest,int nYDest,
InBlock.gif                
int nWidth,int nHeight,IntPtr hObjectSource,
InBlock.gif                
int nXSrc,int nYSrc,int dwRop);
InBlock.gif            [DllImport(
"gdi32.dll")]
InBlock.gif            
public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC,int nWidth, 
InBlock.gif                
int nHeight);
InBlock.gif            [DllImport(
"gdi32.dll")]
InBlock.gif            
public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
InBlock.gif            [DllImport(
"gdi32.dll")]
InBlock.gif            
public static extern bool DeleteDC(IntPtr hDC);
InBlock.gif            [DllImport(
"gdi32.dll")]
InBlock.gif            
public static extern bool DeleteObject(IntPtr hObject);
InBlock.gif            [DllImport(
"gdi32.dll")]
InBlock.gif            
public static extern IntPtr SelectObject(IntPtr hDC,IntPtr hObject);
ExpandedSubBlockEnd.gif        }

InBlock.gif 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Helper class containing User32 API functions
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        private class User32
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            [StructLayout(LayoutKind.Sequential)]
InBlock.gif            
public struct RECT
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
public int left;
InBlock.gif                
public int top;
InBlock.gif                
public int right;
InBlock.gif                
public int bottom;
ExpandedSubBlockEnd.gif            }

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

InBlock.gif
InBlock.gif
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值