C#截取螢幕

來源:互聯網
上載者:User
    /// <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;
}
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.