using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.IO;
namespace capture
{
 /// <summary>
 /// capturepic 的摘要描述。
 /// </summary>
 public class capturepic
 {
  public capturepic()
  {
   //
   // TODO: 在此加入建構函式的程式碼
   //
  }
  [DllImport("gdi32.dll")]
  private static extern IntPtr CreateDC(string lpDriverName, string lpDeviceName, string lpOutput, string lpInitData);
  [DllImport("gdi32.dll")]
  private static extern IntPtr CreateCompatibleDC(IntPtr hDC);
  [DllImport("gdi32.dll")]
  private static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight);
  [DllImport("gdi32.dll")]
  private static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
  [DllImport("gdi32.dll")]
  private static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
  [DllImport("gdi32.dll")]
  public static extern int BitBlt(IntPtr desthDC, int srcX, int srcY, int srcW, int srcH, IntPtr srchDC, int destX, int destY, int op);
  [DllImport("gdi32.dll")]
  private static extern int DeleteDC(IntPtr hDC);
  [DllImport("gdi32.dll")]
  private static extern int DeleteObject(IntPtr hObj);
  public Bitmap CaptureControl(IntPtr SourceDC,int SourceWidth,int SourceHeight)
  {
   return Capture(SourceDC,SourceWidth,SourceHeight);
  }
  public Bitmap CaptureScreen()
  {
IntPtr screen=CreateDC("DISPLAY", "", "", "");
int sourceWidth=GetDeviceCaps(screen, 8);
int sourceHeight=GetDeviceCaps(screen, 10);
Capture(screen,sourceWidth,sourceHeight);
Bitmap ret=Capture(screen,sourceWidth,sourceHeight);
DeleteDC(screen);
return ret;
 }
  static private Bitmap Capture(IntPtr SourceDC,int SourceWidth,int SourceHeight)
 {
IntPtr destDC;
IntPtr BMP, BMPOld;
destDC = CreateCompatibleDC(SourceDC);
BMP = CreateCompatibleBitmap(SourceDC, SourceWidth, SourceHeight);
BMPOld = SelectObject(destDC, BMP);
BitBlt(destDC, 0, 0, SourceWidth, SourceHeight, SourceDC, 0, 0, 13369376);
BMP = SelectObject(destDC, BMPOld);
DeleteDC(destDC);
Bitmap ret = Image.FromHbitmap(BMP);
DeleteObject(BMP);
return ret;
  }
  #region 測試用Sample
  /// <summary>
  /// 測試用Sample
  /// </summary>
  private void capturepic()
  {
   
   capturepic cp=new capturepic();
   //Bitmap bitmap=cp.CaptureControl(button1.CreateGraphics().GetHdc(),button1.Width,button1.Height);
   Bitmap bitmap=cp.CaptureControl(this.CreateGraphics().GetHdc(),this.Width,this.Height);
   //bitmap.Save(@"c:\1.bmp");
   bitmap=cp.test();
   bitmap.Save(@"c:\full.bmp");
  }
  #endregion
 }
}
2011年8月9日 星期二
[C#] capture pic Sample
訂閱:
張貼留言 (Atom)
 
沒有留言:
張貼留言