Created
January 27, 2015 08:10
-
-
Save Jalalx/ce68f41fdde3953115f7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
How to capture the whole screen: | |
var image = ScreenCapture.CaptureDesktop(); | |
image.Save(@"C:\temp\snippetsource.jpg", ImageFormat.Jpeg); | |
How to capture the active window: | |
var image = ScreenCapture.CaptureActiveWindow(); | |
image.Save(@"C:\temp\snippetsource.jpg", ImageFormat.Jpeg); | |
*/ | |
public class ScreenCapture | |
{ | |
[DllImport("user32.dll")] | |
private static extern IntPtr GetForegroundWindow(); | |
[DllImport("user32.dll")] | |
private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect); | |
[StructLayout(LayoutKind.Sequential)] | |
private struct Rect | |
{ | |
public int Left; | |
public int Top; | |
public int Right; | |
public int Bottom; | |
} | |
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] | |
public static extern IntPtr GetDesktopWindow(); | |
public static Image CaptureDesktop() | |
{ | |
return CaptureWindow(GetDesktopWindow()); | |
} | |
public static Bitmap CaptureActiveWindow() | |
{ | |
return CaptureWindow(GetForegroundWindow()); | |
} | |
public static Bitmap CaptureWindow(IntPtr handle) | |
{ | |
var rect = new Rect(); | |
GetWindowRect(handle, ref rect); | |
var bounds = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top); | |
var result = new Bitmap(bounds.Width, bounds.Height); | |
using (var graphics = Graphics.FromImage(result)) | |
{ | |
graphics.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment