日期:2014-05-18  浏览次数:20898 次

[问题]如何将form中的某一区域截取并用image对象保存?
如何将form中的某一区域截取并用image对象保存?

提示:
Graphics.CopyFromScreen();   等

请给出教完整代码.

------解决方案--------------------
from Stoitcho Goutsev 's reply to a similar post
public static System.Drawing.Bitmap PrintWindow(IntPtr hWnd,
PrintWindowFlags flags)
{

//Rectangle screenBounds = Rectangle.Empty;
Rectangle visibleBounds = Rectangle.Empty;
System.Drawing.Bitmap image = null;

using(Graphics grfx = Graphics.FromHdc(GetWindowDC(hWnd)))
{

visibleBounds = Rectangle.Round(grfx.VisibleClipBounds);

}

image = new System.Drawing.Bitmap(
visibleBounds.Width,
visibleBounds.Height);

System.Drawing.Graphics graphics =
System.Drawing.Graphics.FromImage(image);

IntPtr hDC = graphics.GetHdc();
//paint control onto graphics using provided options
try
{
User32.PrintWindow(hWnd, hDC, (uint)flags);
}
finally
{
graphics.ReleaseHdc(hDC);
}

return image;
}

public enum PrintWindowFlags : uint
{
/// <summary>
///
/// </summary>
PW_ALL = 0x00000000,
/// <summary>
/// Only the client area of the window is copied. By default, the entire
/// window is copied.
/// </summary>
PW_CLIENTONLY = 0x00000001
}
}

------解决方案--------------------
可以考虑下使用DrawToBitmap方法。比如:

using(Bitmap bit = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height))
{
this.DrawToBitmap(bit, this.ClientRectangle);
bit.Save( "D:\\temp\bmp.bmp ");
}
------解决方案--------------------
bitmap bm = new bitmap(宽,高);
Graphis g = Graphis.FromImage(bm);
g.DrawImage(老图片,Rect,Rect,GraphicsUnit.Pix);
g.Dispose
------解决方案--------------------
试试:

[DllImportAttribute( "gdi32.dll ")]
public static extern bool BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, System.Int32 dwRop);

public Bitmap Capture(Control ctrl)
{
Graphics g = Graphics.FromHwnd(ctrl.Handle);
Bitmap bitmap = new Bitmap(ctrl.Width, ctrl.Height, g);
Graphics g1 = Graphics.FromImage(bitmap);
IntPtr hdc = g.GetHdc();
IntPtr hdcBitmap = g1.GetHdc();
BitBlt(hdcBitmap, 0, 0, bitmap.Width, bitmap.Height, hdc, 0, 0, 0x00CC0020);
g1.ReleaseHdc(hdcBitmap);
g.ReleaseHdc(hdc);
g1.Dispose();
g.Dispose();
return bitmap;
}
------解决方案--------------------
Bitmap bt = new Bitmap(this.Width, this.Height);
Graphics gr = Graphics.FromImage(bt);
gr.CopyFromScreen(this.Location, new Point(0, 0), this.Size);
bt.Save(@ "D:/temp.bmp ");
刚研究GDI+,对里面许多方法不熟,借用了一下作者的提供方法,这可以保存整个窗体的背景,如果想截取窗体里面特定的矩形,我想应该改一下起始点和size就可以了