此代码几乎可以正常工作。您需要单击该按钮两次,并且仅在第二次单击时才能正常工作。抓取您需要解决的渲染页面存在时间问题。此外,表单必须在前面,因为它是屏幕抓取,所以只抓取屏幕的可见部分。
Option Strict On
Imports System.Drawing
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strHTML As String = "<p>HELLO <span style='color:red'>WORLD</span></p>"
WebBrowser1.DocumentText = strHTML
Dim bmp As Bitmap = GetControlImage(WebBrowser1)
Dim strFilename As String = "C:\Junk\Junk.png"
bmp.Save(strFilename, System.Drawing.Imaging.ImageFormat.Png)
End Sub
Private Declare Function BitBlt _
Lib "gdi32.dll" ( _
ByVal hdcDest As IntPtr, _
ByVal x As Int32, _
ByVal y As Int32, _
ByVal Width As Int32, _
ByVal Height As Int32, _
ByVal hdcSrc As IntPtr, _
ByVal xSrc As Int32, _
ByVal ySrc As Int32, _
ByVal dwRop As Int32 _
) As Boolean
Private Const SRCCOPY As Integer = &HCC0020
Function GetControlImage(ctl As Control) As Bitmap
Dim grpInput As Graphics = ctl.CreateGraphics
' Create a compatible bitmap and get its Graphics object
Dim bmpOutput As New Bitmap(ctl.ClientRectangle.Width, ctl.ClientRectangle.Height, grpInput) 'formImage = New Bitmap(frmForm.ClientRectangle.Width, frmForm.ClientRectangle.Height, formGraphics)
Dim grpOutput As Graphics = Graphics.FromImage(bmpOutput)
' Get the target and source device context handles (hDC)
Dim sourceDC As IntPtr = grpInput.GetHdc
Dim targetDC As IntPtr = grpOutput.GetHdc
' Copy the control's client area
BitBlt(targetDC, 0, 0, ctl.ClientRectangle.Width, ctl.ClientRectangle.Height, sourceDC, ctl.ClientRectangle.X, ctl.ClientRectangle.Y, SRCCOPY)
' Release DCs and dispose objects
grpInput.ReleaseHdc(sourceDC)
grpInput.Dispose()
grpOutput.ReleaseHdc(targetDC)
grpOutput.Dispose()
Return bmpOutput
End Function
End Class