You can import the BitBlt API to handle this problem. Here is a solution offered by Simon Murrell and Lion Shi in the microsoft.public.dotnet.windows.forms newsgroup. The number used below, 13369376, is Int32 SRCCOPY = 0xCC0020;
You can use Gdi32 dll. You can define the BitBlt method found within the Gdi32 dll with the code below.
[System.Runtime.InteropServices.DllImportAttribute('gdi32.dll')]
private static extern bool BitBlt(
ntPtr hdcDest, // handle to destination DC
int nXDest, // x-coord of destination upper-left corner
int nYDest, // y-coord of destination upper-left corner
int nWidth, // width of destination rectangle
int nHeight, // height of destination rectangle
IntPtr hdcSrc, // handle to source DC
int nXSrc, // x-coordinate of source upper-left corner
int nYSrc, // y-coordinate of source upper-left corner
System.Int32 dwRop // raster operation code
);
And you can then use the copy below in a button click event to save the form to an image.
Graphics g1 = this.CreateGraphics();
Image MyImage = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height, g1);
Graphics g2 = Graphics.FromImage(MyImage);
IntPtr dc1 = g1.GetHdc();
IntPtr dc2 = g2.GetHdc();
BitBlt(dc2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height, dc1, 0, 0, 13369376);
g1.ReleaseHdc(dc1);
g2.ReleaseHdc(dc2);
MyImage.Save(@'c:\Captured.bmp', ImageFormat.Bmp);
You will need to use the System.Drawing.Imaging namespace.
Here is VB code posted by Armin Zingler in the microsoft.public.dotnet.languages.vb newsgroup.
Public Class Win32
Public Declare Function BitBlt Lib 'gdi32' Alias 'BitBlt' _
(ByVal hDestDC As Integer, ByVal x As Integer, _
ByVal y As Integer, ByVal nWidth As Integer, _
ByVal nHeight As Integer, ByVal hSrcDC As Integer, _
ByVal xSrc As Integer, ByVal ySrc As Integer, _
ByVal dwRop As Integer) As Integer
Public Declare Function GetWindowDC Lib 'user32' Alias 'GetWindowDC' _
(ByVal hwnd As Integer) As Integer
Public Declare Function ReleaseDC Lib 'user32' Alias 'ReleaseDC' _
(ByVal hwnd As Integer, ByVal hdc As Integer) As Integer
Public Const SRCCOPY As Integer = &HCC0020
End Class
Public Class Hardcopy
Public Shared Function CreateBitmap( _
ByVal Control As Control) _
As Bitmap
Dim gDest As Graphics
Dim hdcDest As IntPtr
Dim hdcSrc As Integer
Dim hWnd As Integer = Control.Handle.ToInt32
CreateBitmap = New Bitmap(Control.Width, Control.Height)
gDest = gDest.FromImage(CreateBitmap)
hdcSrc = Win32.GetWindowDC(hWnd)
hdcDest = gDest.GetHdc
Win32.BitBlt( _
hdcDest.ToInt32, 0, 0, Control.Width, Control.Height, _
hdcSrc, 0, 0, Win32.SRCCOPY _
)
gDest.ReleaseHdc(hdcDest)
Win32.ReleaseDC(hWnd, hdcSrc)
End Function
End Class
’In your Form:
Private Sub Button1_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
Dim bmp As Bitmap
bmp = Hardcopy.CreateBitmap(Me)
bmp.Save('c:\test.bmp')
End Sub
Share with