VB实现抓屏/截图的代码

这段VB代码详细展示了如何实现屏幕抓取和截图功能。包括创建兼容的设备上下文,位图处理,以及捕获窗口和屏幕的不同部分。通过`CaptureWindow`、`CaptureScreen`、`CaptureForm`和`CaptureClient`等函数,可以实现窗口客户区、整个窗口、活动窗口和表单区域的截图。最后,`PrintPictureToFitPage`函数用于将图片按比例打印到页面上。
Attribute VB_Name  =   " ModuleCapturePic "
Option   Explicit
Option  Base  0
'Powered by barenx
Private  Type PALETTEENTRY
   peRed 
As   Byte
   peGreen 
As   Byte
   peBlue 
As   Byte
   peFlags 
As   Byte
End  Type

Private  Type LOGPALETTE
   palVersion 
As   Integer
   palNumEntries 
As   Integer
   palPalEntry(
255 As  PALETTEENTRY   '  Enough for 256 colors.
End  Type

Private  Type GUID
   Data1 
As   Long
   Data2 
As   Integer
   Data3 
As   Integer
   Data4(
7 As   Byte
End  Type

Private   Const  RASTERCAPS  As   Long   =   38
Private   Const  RC_PALETTE  As   Long   =   & H100
Private   Const  SIZEPALETTE  As   Long   =   104

Private  Type RECT
   
Left   As   Long
   Top 
As   Long
   
right   As   Long
   bottom 
As   Long
End  Type

Private   Declare   Function CreateCompatibleDC Lib "gdi32" (ByVal hdc As LongAs Long
Private Declare Function CreateCompatibleBitmap Lib "gdi32" (ByVal hdc As LongByVal nWidth As LongByVal nHeight As LongAs Long
Private Declare Function GetDeviceCaps Lib "gdi32" (ByVal hdc As LongByVal iCapabilitiy As LongAs Long
Private Declare Function GetSystemPaletteEntries Lib "gdi32" (ByVal hdc As LongByVal wStartIndex As LongByVal wNumEntries As Long, lpPaletteEntries As PALETTEENTRY) As Long
Private Declare Function CreatePalette Lib "gdi32" (lpLogPalette As LOGPALETTE) As Long
Private Declare Function SelectObject Lib "gdi32" (ByVal hdc As LongByVal hObject As LongAs Long
Private Declare Function BitBlt Lib "gdi32" (ByVal hDCDest As LongByVal XDest As LongByVal YDest As LongByVal nWidth As LongByVal nHeight As LongByVal hDCSrc As LongByVal xSrc As LongByVal ySrc As LongByVal dwRop As LongAs Long
Private Declare Function DeleteDC Lib "gdi32" (ByVal hdc As LongAs Long
Private Declare Function GetForegroundWindow Lib "user32" () As Long
Private Declare Function SelectPalette Lib "gdi32" (ByVal hdc As LongByVal hPalette As LongByVal bForceBackground As LongAs Long
Private Declare Function RealizePalette Lib "gdi32" (ByVal hdc As LongAs Long
Private Declare Function GetWindowDC Lib "user32" (ByVal hwnd As LongAs Long
Private Declare Function GetDC Lib "user32" (ByVal hwnd As LongAs Long
Private Declare Function GetWindowRect Lib "user32" (ByVal hwnd As Long, lpRect As RECT) As Long
Private Declare Function ReleaseDC Lib "user32" (ByVal hwnd As LongByVal hdc As LongAs Long
Private Declare Function GetDesktopWindow Lib "user32" () As Long

Private Type PicBmp
   Size 
As Long
   Type 
As Long
   hBmp 
As Long
   hPal 
As Long
   Reserved 
As Long
End Type

Private Declare Function OleCreatePictureIndirect Lib "olepro32.dll" (PicDesc As PicBmp, RefIID As GUID, ByVal fPictureOwnsHandle As Long, IPic As IPicture) As Long
'-----------------------------------------------------------------
Private Type POINTAPI
        x 
As Long
        y 
As Long
End Type

Private Type BITMAP '14 bytes
        bmType As Long
        bmWidth 
As Long
        bmHeight 
As Long
        bmWidthBytes 
As Long
        bmPlanes 
As Integer
        bmBitsPixel 
As Integer
        bmBits 
As Long
End Type
'-----------------------------------------------------------------
Private Declare Function CreateBitmap Lib "gdi32" (ByVal nWidth As LongByVal nHeight As LongByVal nPlanes As LongByVal nBitCount As Long, lpBits As Any) As Long
Private Declare Function CreateBitmapIndirect Lib "gdi32" (lpBitmap As BITMAP) As Long
Private Declare Function GetObject Lib "gdi32" Alias "GetObjectA" (ByVal hObject As LongByVal nCount As Long, lpObject As Any) As Long
Private Declare Function DeleteObject Lib "gdi32" (ByVal hObject As LongAs Long
Private Declare Function GetMapMode Lib "gdi32" (ByVal hdc As LongAs Long
Private Declare Function SetMapMode Lib "gdi32" (ByVal hdc As LongByVal nMapMode As LongAs Long
Private Declare Function SetBkColor Lib "gdi32" (ByVal hdc As LongByVal crColor As LongAs Long
Private Declare Function StretchBlt Lib "gdi32" (ByVal hdc As LongByVal x As LongByVal y As LongByVal nWidth As LongByVal nHeight As LongByVal hSrcDC As LongByVal xSrc As LongByVal ySrc As LongByVal nSrcWidth As LongByVal nSrcHeight As LongByVal dwRop As LongAs Long
'-----------------------------------------------------------------
'
==================================================================
'
 函数: ShrinkBmp
'
'
 功能: 伸缩位图
'
'
 入口: dispHdc     DC
'
       hBmp        位图句柄
'
       RatioX      横向比例
'
       RatioY      纵向比例
'
Public Function ShrinkBmp(dispHdc As Long, hBmp As Long, RatioX As Single, RatioY As SingleAs Long
'-----------------------------------------------------------------
    Dim hBmpOut As Long                             ' output bitmap handle
    Dim bm1 As BITMAP, bm2 As BITMAP                ' temporary bitmap structs
    Dim hdcMem1 As Long, hdcMem2 As Long            ' temporary memory bitmap handles...
'
-----------------------------------------------------------------
    hdcMem1 = CreateCompatibleDC(dispHdc)           ' create mem DC compatible to the display DC
    hdcMem2 = CreateCompatibleDC(dispHdc)           ' create mem DC compatible to the display DC
  
    
GetObject hBmp, LenB(bm1), bm1                  ' select bitmap object
  
    
LSet bm2 = bm1                                  ' copy bitmap object
  
    bm2.bmWidth 
= CLng(bm2.bmWidth * RatioX)        ' scale output bitmap width
    bm2.bmHeight = CLng(bm2.bmHeight * RatioY)      ' scale output bitmap height
    bm2.bmWidthBytes = ((((bm2.bmWidth * bm2.bmBitsPixel) + 15 16* 2' calculate bitmap width bytes

    hBmpOut 
= CreateBitmapIndirect(bm2)             ' create handle to output bitmap indirectly from new bm2
    
    SelectObject hdcMem1, hBmp                      
' select original bitmap into mem dc
    SelectObject hdcMem2, hBmpOut                   ' select new bitmap into mem dc

    
' stretch old bitmap into new bitmap
    StretchBlt hdcMem2, 00, bm2.bmWidth, bm2.bmHeight, _
               hdcMem1, 
00, bm1.bmWidth, bm1.bmHeight, vbSrcCopy
    
    DeleteDC hdcMem1                                
' delete memory dc
    DeleteDC hdcMem2                                ' delete memory dc

    ShrinkBmp 
= hBmpOut                             ' return handle to new bitmap
'
-----------------------------------------------------------------
End Function

'==================================================================


'==================================================================
'
 函数: DrawBitmap
'
'
 功能: 将原位图其中的某一区域绘制到目标DC上
'
'
 入口: DestDC      '目标DC
'
       SrcBmp      '原位图句柄
'
       BmpStartX   '区域的起始点X
'
       BmpStartY   '区域的起始点X
'
       BmpWidth    '区域的宽
'
       BmpHeight   '区域的高
'
Public Sub DrawBitmap(ByVal DestDC&, _
               
ByVal SrcBmp&, _
               
Optional ByVal BmpStartX& = 0, _
               
Optional ByVal BmpStartY& = 0, _
               
Optional ByVal BmpWidth& = -1, _
               
Optional ByVal BmpHeight& = -1, _
               
Optional ByVal ToStartX& = 0, _
               
Optional ByVal ToStartY& = 0)
'-----------------------------------------------------------------
    Dim udtBitMap As BITMAP
    
Dim SrcDCTemp&
    
Dim SrcOldBmp&
    
    SrcDCTemp 
= CreateCompatibleDC(DestDC)      'Create a temporary HDC compatible to the Destination HDC
    SrcOldBmp = SelectObject(SrcDCTemp, SrcBmp) 'Select the bitmap
    GetObject SrcBmp, Len(udtBitMap), udtBitMap
    
    
'Get bmWidth and bmHeight
    With udtBitMap
        
If BmpWidth = -1 Then BmpWidth = .bmWidth
        
If BmpHeight = -1 Then BmpHeight = .bmHeight
    
End With
    
    
'Paint SrcBmp to DestDC
    BitBlt DestDC, ToStartX, ToStartY, BmpWidth, BmpHeight, SrcDCTemp, BmpStartX, BmpStartY, vbSrcCopy
    
    
'Release resource
    SelectObject SrcDCTemp, SrcOldBmp
    DeleteDC SrcDCTemp
'-----------------------------------------------------------------
End Sub

'==================================================================

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
'
 CreateBitmapPicture
'
    - Creates a bitmap type Picture object from a bitmap and
'
      palette.
'
'
 hBmp
'
    - Handle to a bitmap.
'
'
 hPal
'
    - Handle to a Palette.
'
    - Can be null if the bitmap doesn't use a palette.
'
'
 Returns
'
    - Returns a Picture object containing the bitmap.
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'

Private Function CreateBitmapPicture(ByVal hBmp As LongByVal hPal As LongAs Picture
  
Dim r As Long

   
Dim pic As PicBmp
   
' IPicture requires a reference to "Standard OLE Types."
   Dim IPic As IPicture
   
Dim IID_IDispatch As GUID

   
' Fill in with IDispatch Interface ID.
   With IID_IDispatch
      .Data1 
= &H20400
      .Data4(
0= &HC0
      .Data4(
7= &H46
   
End With

   
' Fill Pic with necessary parts.
   With pic
      .Size 
= Len(pic)          ' Length of structure.
      .Type = vbPicTypeBitmap   ' Type of Picture (bitmap).
      .hBmp = hBmp              ' Handle to bitmap.
      .hPal = hPal              ' Handle to palette (may be null).
   End With

   
' Create Picture object.
   r = OleCreatePictureIndirect(pic, IID_IDispatch, 1, IPic)

   
' Return the new Picture object.
   Set CreateBitmapPicture = IPic
End Function


'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
'
 CaptureWindow
'
    - Captures any portion of a window.
'
'
 hWndSrc
'
    - Handle to the window to be captured.
'
'
 Client
'
    - If True CaptureWindow captures from the client area of the
'
      window.
'
    - If False CaptureWindow captures from the entire window.
'
'
 LeftSrc, TopSrc, WidthSrc, HeightSrc
'
    - Specify the portion of the window to capture.
'
    - Dimensions need to be specified in pixels.
'
'
 Returns
'
    - Returns a Picture object containing a bitmap of the specified
'
      portion of the window that was captured.
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
'''''
'

  
Public Function CaptureWindow(ByVal hWndSrc As LongByVal Client As BooleanByVal LeftSrc As LongByVal TopSrc As LongByVal WidthSrc As LongByVal HeightSrc As LongAs Picture

  
Dim hDCMemory As Long
  
Dim hBmp As Long
  
Dim hBmpPrev As Long
  
Dim r As Long
  
Dim hDCSrc As Long
  
Dim hPal As Long
  
Dim hPalPrev As Long
  
Dim RasterCapsScrn As Long
  
Dim HasPaletteScrn As Long
  
Dim PaletteSizeScrn As Long
  
Dim LogPal As LOGPALETTE

   
' Depending on the value of Client get the proper device context.
   If Client Then
      hDCSrc 
= GetDC(hWndSrc) ' Get device context for client area.
   Else
      hDCSrc 
= GetWindowDC(hWndSrc) ' Get device context for entire
                                    ' window.
   End If

   
' Create a memory device context for the copy process.
   hDCMemory = CreateCompatibleDC(hDCSrc)
   
' Create a bitmap and place it in the memory DC.
   hBmp = CreateCompatibleBitmap(hDCSrc, WidthSrc, HeightSrc)
   hBmpPrev 
= SelectObject(hDCMemory, hBmp)

   
' Get screen properties.
   RasterCapsScrn = GetDeviceCaps(hDCSrc, RASTERCAPS) ' Raster
                                                      ' capabilities.
   HasPaletteScrn = RasterCapsScrn And RC_PALETTE       ' Palette
                                                        ' support.
   PaletteSizeScrn = GetDeviceCaps(hDCSrc, SIZEPALETTE) ' Size of
                                                        ' palette.

   
' If the screen has a palette make a copy and realize it.
   If HasPaletteScrn And (PaletteSizeScrn = 256Then
      
' Create a copy of the system palette.
      LogPal.palVersion = &H300
      LogPal.palNumEntries 
= 256
      r 
= GetSystemPaletteEntries(hDCSrc, 0256, LogPal.palPalEntry(0))
      hPal 
= CreatePalette(LogPal)
      
' Select the new palette into the memory DC and realize it.
      hPalPrev = SelectPalette(hDCMemory, hPal, 0)
      r 
= RealizePalette(hDCMemory)
   
End If

   
' Copy the on-screen image into the memory DC.
   r = BitBlt(hDCMemory, 00, WidthSrc, HeightSrc, hDCSrc, LeftSrc, TopSrc, vbSrcCopy)

' Remove the new copy of the  on-screen image.
   hBmp = SelectObject(hDCMemory, hBmpPrev)

   
' If the screen has a palette get back the palette that was
   ' selected in previously.
   If HasPaletteScrn And (PaletteSizeScrn = 256Then
      hPal 
= SelectPalette(hDCMemory, hPalPrev, 0)
   
End If

   
' Release the device context resources back to the system.
   r = DeleteDC(hDCMemory)
   r 
= ReleaseDC(hWndSrc, hDCSrc)

   
' Call CreateBitmapPicture to create a picture object from the
   ' bitmap and palette handles. Then return the resulting picture
   ' object.
   Set CaptureWindow = CreateBitmapPicture(hBmp, hPal)
End Function


'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
'
 CaptureScreen
'
    - Captures the entire screen.
'
'
 Returns
'
    - Returns a Picture object containing a bitmap of the screen.
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
Public Function CaptureScreen() As Picture
  
Dim hWndScreen As Long

   
' Get a handle to the desktop window.
   hWndScreen = GetDesktopWindow()

   
' Call CaptureWindow to capture the entire desktop give the handle
   ' and return the resulting Picture object.

   
Set CaptureScreen = CaptureWindow(hWndScreen, False00, Screen.Width  Screen.TwipsPerPixelX, Screen.Height  Screen.TwipsPerPixelY)
End Function


'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
'
 CaptureForm
'
    - Captures an entire form including title bar and border.
'
'
 frmSrc
'
    - The Form object to capture.
'
'
 Returns
'
    - Returns a Picture object containing a bitmap of the entire
'
      form.
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
Public Function CaptureForm(frmSrc As Form) As Picture
   
' Call CaptureWindow to capture the entire form given its window
   ' handle and then return the resulting Picture object.
   Set CaptureForm = CaptureWindow(frmSrc.hwnd, False00, frmSrc.ScaleX(frmSrc.Width, vbTwips, vbPixels), frmSrc.ScaleY(frmSrc.Height, vbTwips, vbPixels))
End Function


'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
'
 CaptureClient
'
    - Captures the client area of a form.
'
'
 frmSrc
'
    - The Form object to capture.
'
'
 Returns
'
    - Returns a Picture object containing a bitmap of the form's
'
      client area.
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
Public Function CaptureClient(frmSrc As Form) As Picture
   
' Call CaptureWindow to capture the client area of the form given
   ' its window handle and return the resulting Picture object.
   Set CaptureClient = CaptureWindow(frmSrc.hwnd, True00, frmSrc.ScaleX(frmSrc.ScaleWidth, frmSrc.ScaleMode, vbPixels), frmSrc.ScaleY(frmSrc.ScaleHeight, frmSrc.ScaleMode, vbPixels))
End Function


'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
'
 CaptureActiveWindow
'
    - Captures the currently active window on the screen.
'
'
 Returns
'
    - Returns a Picture object containing a bitmap of the active
'
      window.
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
Public Function CaptureActiveWindow() As Picture

    
Dim hWndActive As Long
    
Dim r As Long
    
    
Dim RectActive As RECT
    
    
' Get a handle to the active/foreground window.
    hWndActive = GetForegroundWindow()
    
    
' Get the dimensions of the window.
    r = GetWindowRect(hWndActive, RectActive)
    
    
' Call CaptureWindow to capture the active window given its
    ' handle and return the Resulting Picture object.
    Set CaptureActiveWindow = CaptureWindow(hWndActive, False00, RectActive.right - RectActive.Left, RectActive.bottom - RectActive.Top)
End Function


'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
'
 PrintPictureToFitPage
'
    - Prints a Picture object as big as possible.
'
'
 Prn
'
    - Destination Printer object.
'
'
 Pic
'
    - Source Picture object.
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
Public Sub PrintPictureToFitPage(Prn As Printer, pic As Picture)
    
    
Const vbHiMetric As Integer = 8
    
Dim PicRatio As Double
    
Dim PrnWidth As Double
    
Dim PrnHeight As Double
    
Dim PrnRatio As Double
    
Dim PrnPicWidth As Double
    
Dim PrnPicHeight As Double
    
    
' Determine if picture should be printed in landscape or portrait
    ' and set the orientation.
    If pic.Height >= pic.Width Then
        Prn.Orientation 
= vbPRORPortrait   ' Taller than wide.
    Else
        Prn.Orientation 
= vbPRORLandscape  ' Wider than tall.
    End If
    
    
' Calculate device independent Width-to-Height ratio for picture.
    PicRatio = pic.Width / pic.Height
    
    
' Calculate the dimentions of the printable area in HiMetric.
    PrnWidth = Prn.ScaleX(Prn.ScaleWidth, Prn.ScaleMode, vbHiMetric)
    PrnHeight 
= Prn.ScaleY(Prn.ScaleHeight, Prn.ScaleMode, vbHiMetric)
    
' Calculate device independent Width to Height ratio for printer.
    PrnRatio = PrnWidth / PrnHeight
    
    
' Scale the output to the printable area.
    If PicRatio >= PrnRatio Then
        
' Scale picture to fit full width of printable area.
        PrnPicWidth = Prn.ScaleX(PrnWidth, vbHiMetric, Prn.ScaleMode)
        PrnPicHeight 
= Prn.ScaleY(PrnWidth / PicRatio, vbHiMetric, Prn.ScaleMode)
    
Else
        
' Scale picture to fit full height of printable area.
        PrnPicHeight = Prn.ScaleY(PrnHeight, vbHiMetric, Prn.ScaleMode)
        PrnPicWidth 
= Prn.ScaleX(PrnHeight * PicRatio, vbHiMetric, Prn.ScaleMode)
    
End If
    
    
' Print the picture using the PaintPicture method.
    Prn.PaintPicture pic, 00, PrnPicWidth, PrnPicHeight
End Sub

'-------------------------------------------------------------------

 
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值