用 Visual Basic 轻松地以编程方式捕获屏幕截图






3.76/5 (11投票s)
这段代码展示了一种将桌面捕获到文件的简单方法。
引言
这段代码片段演示了如何以最少的代码将桌面或任何窗口捕获到BMP文件。它还展示了一种将设备上下文 (DC) 保存到硬盘文件的简洁方法。
代码解释
要捕获窗口,我们可以使用Windows API中提供的内置函数。要获取此API中可用函数的列表,请使用 API 查看器工具,该工具可以从 插件管理器 添加到Visual Studio。以下是API中使用的一些函数列表
GetWindowDc
- 获取DC的设备上下文CreateCompatibleDc
- 在内存中创建设备上下文BitBlt
- 执行从一个DC到另一个DC的像素级数据传输
如何在Visual Basic中使用API函数?
在使用API函数之前,需要先声明它们。最好的方法是在模块文件中声明所有必需的函数,以便任何窗体都可以访问它们。声明示例
Private Declare Function GetWindowDC Lib "user32" Alias "GetWindowDC"
(ByVal hwnd As Long) As Long
对于所有其他函数的声明语法,请使用“API 查看器”工具。
代码算法简要说明
- 计算要复制的窗口的宽度和高度
- 检索窗口的设备上下文,也称为DC
- 使用API函数(
CreateCompatibleDC
)在内存中创建一个新的设备上下文 (DC) - 在新建的DC中使用API创建一个位图对象
- 使用API函数
BitBlt
将图像数据从窗口DC复制到内存DC - 从位图对象创建Ole图片对象
- 使用VB函数
saveimage
将Olepicture
保存到文件
Public Function GetWindowScreenshot_
(WndHandle As Long, SavePath As String, Optional BringFront As Integer = 1) As Long
'
' Function to create screeenshot of specified window and store at specified path
'
On Error GoTo ErrorHandler
Dim hDCSrc As Long
Dim hDCMemory As Long
Dim hBmp As Long
Dim hBmpPrev As Long
Dim WidthSrc As Long
Dim HeightSrc As Long
Dim Pic As PicBmp
Dim IPic As IPicture
Dim IID_IDispatch As guid
Dim rc As RECT
Dim pictr As PictureBox
'Bring window on top of all windows if specified
If BringFront = 1 Then BringWindowToTop WndHandle
'Get Window Size
GetWindowRect WndHandle, rc
WidthSrc = rc.Right - rc.Left
HeightSrc = rc.Bottom - rc.Top
'Get Window device context
hDCSrc = GetWindowDC(WndHandle)
'create a memory device context
hDCMemory = CreateCompatibleDC(hDCSrc)
'create a bitmap compatible with window hdc
hBmp = CreateCompatibleBitmap(hDCSrc, WidthSrc, HeightSrc)
'copy newly created bitmap into memory device context
hBmpPrev = SelectObject(hDCMemory, hBmp)
'copy window window hdc to memory hdc
Call BitBlt(hDCMemory, 0, 0, WidthSrc, HeightSrc, _
hDCSrc, 0, 0, vbSrcCopy)
'Get Bmp from memory Dc
hBmp = SelectObject(hDCMemory, hBmpPrev)
'release the created objects and free memory
Call DeleteDC(hDCMemory)
Call ReleaseDC(WndHandle, hDCSrc)
'fill in OLE 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 = 0& 'Handle to palette (may be null)
End With
'create OLE Picture object
Call OleCreatePictureIndirect(Pic, IID_IDispatch, 1, IPic)
'return the new Picture object
SavePicture IPic, SavePath
GetWindowScreenshot = 1
Exit Function
ErrorHandler:
GetWindowScreenshot = 0
End Function
更多图形相关代码
更多易于使用且免费的VB 6代码片段在此处提供。
下载带有演示应用程序的源代码
可以从此处下载带有完整源代码的演示应用程序。