Hi Kevin,
There are two methods that I know for capturing the graphics of a Control.
Both have been included below (for future reference), but only the first will
work for panels.
The first one takes a copy of the Control's surface as it exists. This
means that the Control must be visible and with no other windows on top.
The other one works by fooling the Control into doing its Paint onto a
supplied Bitmap. This works fine for many Controls but not for Panels or
GroupBoxes (and probably not for other container Controls).
In use:
Dim bmpPanel As Bitmap = CaptureControl (pnlSomething)
Regards,
Fergus
<code>
'===============================================================
Public Const SRCCOPY As Integer = &HCC0020
Public Declare Function BitBlt Lib "gdi32" ( _
ByVal hDestDC As IntPtr, _
ByVal x As Integer, _
ByVal y As Integer, _
ByVal nWidth As Integer, _
ByVal nHeight As Integer, _
ByVal hSrcDC As IntPtr, _
ByVal xSrc As Integer, _
ByVal ySrc As Integer, _
ByVal dwRop As Integer _
) As Integer
'===============================================================
Public Function CaptureControl(ByVal c As Control) As Bitmap
Dim bmp As Bitmap
Dim gDest, gSource As Graphics
Dim hdcSource, hdcDest As IntPtr
bmp = New Bitmap(c.Width, c.Height)
gSource = c.CreateGraphics
Try
gDest = Graphics.FromImage(bmp)
Try
hdcSource = gSource.GetHdc
Try
hdcDest = gDest.GetHdc
Try
BitBlt( _
hdcDest, 0, 0, _
c.Width, c.Height, _
hdcSource, 0, 0, SRCCOPY _
)
Finally
gDest.ReleaseHdc(hdcDest)
End Try
Finally
gSource.ReleaseHdc(hdcSource)
End Try
Finally
gDest.Dispose()
End Try
Finally
gSource.Dispose()
End Try
Return bmp
End Function
'===============================================================
Public Function PaintControlToBitmap (oControl As Control) As Bitmap
Dim OnPaintMethod As MethodInfo
OnPaintMethod = oControl.GetType.GetMethod ("OnPaint", _
BindingFlags.Instance Or BindingFlags.NonPublic)
If Not OnPaintMethod Is Nothing Then
Dim bmpControl As New Bitmap (oControl.Width, oControl.Height)
Dim gr As Graphics = Graphics.FromImage (bmpControl)
Dim PaintEventArgs As New PaintEventArgs (gr, _
New Rectangle(0, 0, oControl.Width, oControl.Height))
OnPaintMethod.Invoke(oControl, New Object() {PaintEventArgs})
gr.Dispose
Return bmpControl
End If
End Function
'===============================================================
Public Sub CopyGraphics (gSource As Graphics, gDest As Graphics, _
Width As Integer, Height As
Integer)
Dim hdcSource, hdcDest As IntPtr
hdcSource = gSource.GetHdc
Try
hdcDest = gDest.GetHdc
Try
BitBlt( _
gDest.GetHdc, 0, 0, _
Width, Height, _
gSource.GetHdc, 0, 0, SRCCOPY _
)
Finally
gDest.ReleaseHdc(hdcDest)
End Try
Finally
gSource.ReleaseHdc(hdcSource)
End Try
End Sub
</code>