介绍:
做项目中,遇到需要截取界面图形的内容,查找了所有的Graphics函数,
都没有此功能。只能用GDI32中的BitBlt来解决。
应用需要调用的函数
class GDI32
{
[DllImport("GDI32.dll")]
public static extern bool BitBlt(int hdcDest,int nXDest,int nYDest,
int nWidth,int nHeight,int hdcSrc,
int nXSrc,int nYSrc,int dwRop);
[DllImport("GDI32.dll")]
public static extern int CreateCompatibleBitmap(int hdc,int nWidth,
int nHeight);
[DllImport("GDI32.dll")]
public static extern int CreateCompatibleDC(int hdc);
[DllImport("GDI32.dll")]
public static extern bool DeleteDC(int hdc);
[DllImport("GDI32.dll")]
public static extern bool DeleteObject(int hObject);
[DllImport("GDI32.dll")]
public static extern int GetDeviceCaps(int hdc,int nIndex);
[DllImport("GDI32.dll")]
public static extern int SelectObject(int hdc,int hgdiobj);
public static void Cleanup(int hBitmap,int hdcSrc,int hdcDest)
{
// Release the device context resources back to the system
User32.ReleaseDC(User32.GetDesktopWindow(),hdcSrc);
GDI32.DeleteDC(hdcDest);
GDI32.DeleteObject(hBitmap);
}
public static void SaveImageAs(int hBitmap,string fileName,ImageFormat imageFormat)
{
// Create a bitmap from the Windows handle
Bitmap image =
new Bitmap(Image.FromHbitmap(new IntPtr(hBitmap)),
Image.FromHbitmap(new IntPtr(hBitmap)).Width,
Image.FromHbitmap(new IntPtr(hBitmap)).Height);
image.Save(fileName,imageFormat);
}
}
class User32
{
[DllImport("User32.dll")]
public static extern int GetDesktopWindow();
[DllImport("User32.dll")]
public static extern int GetWindowDC(int hWnd);
[DllImport("User32.dll")]
public static extern int ReleaseDC(int hWnd,int hDC);
}
具体实现的方式
和C++中的代码类似
int hdcSrc = User32.GetWindowDC((int)this.control.Handle), // 获得控件的Handle
hdcDest = GDI32.CreateCompatibleDC(hdcSrc), // 创建兼容DC
hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc,
this.control.Width,this.control.Height);//创建
GDI32.SelectObject(hdcDest,hBitmap); // 选择
GDI32.BitBlt(hdcDest,0,0,this.control.Width,
this.control.Height,
hdcSrc,0,0,0x00CC0020);//绘制图形
Bitmap image = new Bitmap(Image.FromHbitmap(new IntPtr(hBitmap)),
Image.FromHbitmap(new IntPtr(hBitmap)).Width,
Image.FromHbitmap(new IntPtr(hBitmap)).Height);//转换为.net的Image类型
GDI32.Cleanup(hBitmap,hdcSrc,hdcDest);//清除句柄