截取控件界面
介紹:
?做項目中,遇到需要截取界面圖形的內容,查找了所有的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);//清除句柄
轉載于:https://www.cnblogs.com/wanghualiang/archive/2006/01/20/320709.html
總結
- 上一篇: 揩油
- 下一篇: 《我的成长》6月下2009年第7期(总第