截取桌面圖像,比較簡單,只需要簡單的調用Graphics的CopyFromScreen方法即可以實現;
關於將圖像繪製到窗口上很容易實現,但是卻很少看到有文章介紹從窗口上截取圖像的。下面主要介紹一下關於窗口圖像截取的方法。
要截取窗口的圖像,需要用到系統提供的BitBlt函數,這個函數的作用就是從源設備的上下文中拷貝一張Bitmap圖像至目標設備。具體參數介紹請參見MSDN文檔
下面是C#對該函數的引入操作:
[DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern int BitBlt(HandleRef hDC, int x, int y, int nWidth, int nHeight, HandleRef hSrcDC, int xSrc, int ySrc, int dwRop);
具體操作代碼參見如下:
Graphics gSrc = this.CreateGraphics(); //創建窗體的Graphics對象
HandleRef hDcSrc = new HandleRef(null, gSrc.GetHdc());
int width = this.Width-SystemInformation.FrameBorderSize.Width; //獲取寬度
int height = this.Height-SystemInformation.FrameBorderSize.Height; //獲取高度
const int SRCCOPY = 0xcc0020; //複製圖塊的光柵操作碼
Bitmap bmSave = new Bitmap(width, height); //用於保存圖片的位圖對象
Graphics gSave = Graphics.FromImage(bmSave); //創建該位圖的Graphics對象
HandleRef hDcSave = new HandleRef(null, gSave.GetHdc()); //得到句柄
BitBlt(hDcSave, 0, 0, width, height, hDcSrc, 0, 0, SRCCOPY);
如此操作,當前窗體的圖像即被保存之bmSave中。
下面提供一段詳細的代碼
窗體設計部分代碼就省略了,測試窗體圖像如下: