ScreenCapture sc = new ScreenCapture();
// capture entire screen, and save it to a file
Image img = sc.CaptureScreen();
// display image in a Picture control named imageDisplay
this.imageDisplay.Image = img;
// capture this window, and save it
sc.CaptureWindowToFile(this.Handle,"C:\\temp2.gif",ImageFormat.Gif);
public enum enmScreenCaptureMode
{
Screen,
Window
}
class ScreenCapturer
{
[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;
}
public Bitmap Capture(enmScreenCaptureMode screenCaptureMode = enmScreenCaptureMode.Window)
{
Rectangle bounds;
if (screenCaptureMode == enmScreenCaptureMode.Screen)
{
bounds = Screen.GetBounds(Point.Empty);
CursorPosition = Cursor.Position;
}
else
{
var foregroundWindowsHandle = GetForegroundWindow();
var rect = new Rect();
GetWindowRect(foregroundWindowsHandle, ref rect);
bounds = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
CursorPosition = new Point(Cursor.Position.X - rect.Left, Cursor.Position.Y - rect.Top);
}
var result = new Bitmap(bounds.Width, bounds.Height);
using (var g = Graphics.FromImage(result))
{
g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
}
return result;
}
public Point CursorPosition
{
get;
protected set;
}
}
KvanTTT的代码运行得很好。我对它进行了一些扩展,以允许在保存格式上有更多的灵活性,以及通过hWnd、. net Control/Form保存的能力。您可以获得位图或保存到文件,有几个选项。
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace MosaiqPerformanceMonitor {
public enum CaptureMode {
Screen, Window
}
public static class ScreenCapturer {
[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();
/// <summary> Capture Active Window, Desktop, Window or Control by hWnd or .NET Contro/Form and save it to a specified file. </summary>
/// <param name="filename">Filename.
/// <para>* If extension is omitted, it's calculated from the type of file</para>
/// <para>* If path is omitted, defaults to %TEMP%</para>
/// <para>* Use %NOW% to put a timestamp in the filename</para></param>
/// <param name="mode">Optional. The default value is CaptureMode.Window.</param>
/// <param name="format">Optional file save mode. Default is PNG</param>
public static void CaptureAndSave(string filename, CaptureMode mode = CaptureMode.Window, ImageFormat format = null) {
ImageSave(filename, format, Capture(mode));
}
/// <summary> Capture a specific window (or control) and save it to a specified file. </summary>
/// <param name="filename">Filename.
/// <para>* If extension is omitted, it's calculated from the type of file</para>
/// <para>* If path is omitted, defaults to %TEMP%</para>
/// <para>* Use %NOW% to put a timestamp in the filename</para></param>
/// <param name="handle">hWnd (handle) of the window to capture</param>
/// <param name="format">Optional file save mode. Default is PNG</param>
public static void CaptureAndSave(string filename, IntPtr handle, ImageFormat format = null) {
ImageSave(filename, format, Capture(handle));
}
/// <summary> Capture a specific window (or control) and save it to a specified file. </summary>
/// <param name="filename">Filename.
/// <para>* If extension is omitted, it's calculated from the type of file</para>
/// <para>* If path is omitted, defaults to %TEMP%</para>
/// <para>* Use %NOW% to put a timestamp in the filename</para></param>
/// <param name="c">Object to capture</param>
/// <param name="format">Optional file save mode. Default is PNG</param>
public static void CaptureAndSave(string filename, Control c, ImageFormat format = null) {
ImageSave(filename, format, Capture(c));
}
/// <summary> Capture the active window (default) or the desktop and return it as a bitmap </summary>
/// <param name="mode">Optional. The default value is CaptureMode.Window.</param>
public static Bitmap Capture(CaptureMode mode = CaptureMode.Window) {
return Capture(mode == CaptureMode.Screen ? GetDesktopWindow() : GetForegroundWindow());
}
/// <summary> Capture a .NET Control, Form, UserControl, etc. </summary>
/// <param name="c">Object to capture</param>
/// <returns> Bitmap of control's area </returns>
public static Bitmap Capture(Control c) {
return Capture(c.Handle);
}
/// <summary> Capture a specific window and return it as a bitmap </summary>
/// <param name="handle">hWnd (handle) of the window to capture</param>
public static Bitmap Capture(IntPtr handle) {
Rectangle bounds;
var rect = new Rect();
GetWindowRect(handle, ref rect);
bounds = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
CursorPosition = new Point(Cursor.Position.X - rect.Left, Cursor.Position.Y - rect.Top);
var result = new Bitmap(bounds.Width, bounds.Height);
using (var g = Graphics.FromImage(result))
g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
return result;
}
/// <summary> Position of the cursor relative to the start of the capture </summary>
public static Point CursorPosition;
/// <summary> Save an image to a specific file </summary>
/// <param name="filename">Filename.
/// <para>* If extension is omitted, it's calculated from the type of file</para>
/// <para>* If path is omitted, defaults to %TEMP%</para>
/// <para>* Use %NOW% to put a timestamp in the filename</para></param>
/// <param name="format">Optional file save mode. Default is PNG</param>
/// <param name="image">Image to save. Usually a BitMap, but can be any
/// Image.</param>
static void ImageSave(string filename, ImageFormat format, Image image) {
format = format ?? ImageFormat.Png;
if (!filename.Contains("."))
filename = filename.Trim() + "." + format.ToString().ToLower();
if (!filename.Contains(@"\"))
filename = Path.Combine(Environment.GetEnvironmentVariable("TEMP") ?? @"C:\Temp", filename);
filename = filename.Replace("%NOW%", DateTime.Now.ToString("yyyy-MM-dd@hh.mm.ss"));
image.Save(filename, format);
}
}
}
static void ImageSave(string filename, ImageFormat format, Image image, SaveFileDialog saveFileDialog1)
{
saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
saveFileDialog1.Title = "Enregistrer un image";
saveFileDialog1.ShowDialog();
// If the file name is not an empty string open it for saving.
if (saveFileDialog1.FileName != "")
{
// Saves the Image via a FileStream created by the OpenFile method.
System.IO.FileStream fs =
(System.IO.FileStream)saveFileDialog1.OpenFile();
// Saves the Image in the appropriate ImageFormat based upon the
// File type selected in the dialog box.
// NOTE that the FilterIndex property is one-based.
switch (saveFileDialog1.FilterIndex)
{
case 1:
image.Save(fs,
System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case 2:
image.Save(fs,
System.Drawing.Imaging.ImageFormat.Bmp);
break;
case 3:
image.Save(fs,
System.Drawing.Imaging.ImageFormat.Gif);
break;
}
fs.Close();
}
}
你的button_click事件应该像这样编码…
private void btnScreenShot_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
ScreenCapturer.CaptureAndSave(filename, mode, format, saveFileDialog1);
}//
private void btnCapture_Click(object sender, EventArgs e)
{
using(Bitmap bitmap = webBrowser.GetScreenshot())
bitmap.ShowSaveFileDialog();
//exit from using block will release bitmap resources even if exception occured
}
public class ScreenCapture
{
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetDesktopWindow();
[StructLayout(LayoutKind.Sequential)]
private struct Rect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[DllImport("user32.dll")]
private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);
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;
}
}
如何捕捉整个屏幕:
var image = ScreenCapture.CaptureDesktop();
image.Save(@"C:\temp\snippetsource.jpg", ImageFormat.Jpeg);
如何捕获活动窗口:
var image = ScreenCapture.CaptureActiveWindow();
image.Save(@"C:\temp\snippetsource.jpg", ImageFormat.Jpeg);
// Shot size = screen size
Size shotSize = Screen.PrimaryScreen.Bounds.Size;
// the upper left point in the screen to start shot
// 0,0 to get the shot from upper left point
Point upperScreenPoint = new Point(0, 0);
// the upper left point in the image to put the shot
Point upperDestinationPoint = new Point(0, 0);
// create image to get the shot in it
Bitmap shot = new Bitmap(shotSize.Width, shotSize.Height);
// new Graphics instance
Graphics graphics = Graphics.FromImage(shot);
// get the shot by Graphics class
graphics.CopyFromScreen(upperScreenPoint, upperDestinationPoint, shotSize);
// return the image
pictureBox1.Image = shot;
public class ScreenCapture
{
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetDesktopWindow();
[StructLayout(LayoutKind.Sequential)]
private struct Rect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[DllImport("user32.dll")]
private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);
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);
GetScale getScale = new GetScale();
var bounds = new Rectangle(rect.Left, rect.Top, (int)((rect.Right - rect.Left)* getScale.getScalingFactor()), (int)((rect.Bottom - rect.Top )* getScale.getScalingFactor()));
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;
}
}