C#截取屏幕

/// <summary>
/// 截取屏幕
/// </summary>
class ScreenGrab
{
#region Functional imports for ScreenGrab functionality
[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);
[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);
#endregion

// Captures the current on-screen representation using Windows API calls
public Bitmap CaptureScreen()
{
// Provides a pointer to the visual representation of the desktop window
int source = GetWindowDC(GetDesktopWindow());
// Secures the image using CreateCompatibleBitmap
int bitmap = CreateCompatibleBitmap(source, GetDeviceCaps(source, 8), GetDeviceCaps(source, 10));

int destination = CreateCompatibleDC(source);

SelectObject(destination, bitmap);
BitBlt(destination,
0, 0, GetDeviceCaps(source, 8), GetDeviceCaps(source, 10), source, 0, 0, 0x00CC0020);
Bitmap image
= GetImage(bitmap);
Cleanup(bitmap, source, destination);
return image;
}

private void Cleanup(int bitmap, int source, int destination)
{
ReleaseDC(GetDesktopWindow(), source);
DeleteDC(destination);
DeleteObject(bitmap);
}

private Bitmap GetImage(int hBitmap)
{
Bitmap image
= new Bitmap(Image.FromHbitmap(new IntPtr(hBitmap)), Image.FromHbitmap(new IntPtr(hBitmap)).Width,
Image.FromHbitmap(
new IntPtr(hBitmap)).Height);
return image;
}
}
posted on 2008-09-05 18:21  迷你软件  阅读(1610)  评论(0编辑  收藏  举报

本网站绝大部分资源来源于Internet,本站所有作品版权归原创作者所有!!如有以下内容:章节错误、非法内容、作者署名出错、版权疑问、作品内容有违相关法律等请及时与我联系. 我将在第一时间做出响应!本站所有文章观点不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。