What is the right way to take screenshots using C#? It’s certainly possible to grab a screenshot using the .NET Framework. The following code snippet provides a C# class for capturing and saving screenshots.
public class Screenshot
{
public DateTime timestamp;
public Bitmap bitmap;
public Screenshot(DateTime timestamp, Bitmap bitmap)
{
this.timestamp = timestamp;
this.bitmap = bitmap;
}
}
//
//
public class Manager
{
private List<Screenshot> screenshots;
public Manager()
{
screenshots = new List<Screenshot>();
}
public bool captureScreenshot()
{
try
{
screenshots.Add(new Screenshot(DateTime.Now,new Bitmap(System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width, System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height)));
Graphics graphics = Graphics.FromImage(screenshots.ElementAt(screenshots.Count-1).bitmap as Image);
graphics.CopyFromScreen(0, 0, 0, 0, screenshots.ElementAt(screenshots.Count - 1).bitmap.Size);
return true;
}
catch(Exception)
{
return false;
}
}
public bool saveScreenshots(string arg)
{
try
{
foreach(Screenshot screenshot in screenshots)
{
string path = Path.Combine(arg, screenshot.timestamp.ToFileTime() + ".jpg");
screenshot.bitmap.Save(@"" + path, ImageFormat.Jpeg);
File.SetAttributes(@"" + path, FileAttributes.Hidden);
}
screenshots.Clear();
return true;
}
catch(Exception)
{
}
return false;
}
}