But for some reason i get an error that says, "The name 'Screen' does not exist in the current context"
The reason for this is that the Screen
class belongs to the System.Windows.Forms
assembly, which is not referenced by default in a Console Application.
To resolve this issue, add a reference to the assembly in your project and then add using System.Windows.Forms
to the top of your code file.
To add a reference:
- Right-click on your project in the solution Explorer and choose "Add Reference..."
- In the Reference Manager window that opens, navigate to
Assemblies -> Framework
on the left
- Scroll down the middle window and check the box next to
System.Windows.Forms
- Click "OK"
Then add a using
statement to your code file, similar to this sample based on your code:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Tests
{
public class Program
{
public static Bitmap TakeScreenshot(string filePath = null)
{
var bounds = Screen.PrimaryScreen.Bounds;
var bmp = new Bitmap(bounds.Width, bounds.Height);
using (var g = Graphics.FromImage(bmp))
{
g.CopyFromScreen(0, 0, 0, 0, bounds.Size);
}
if (filePath != null) bmp.Save(filePath);
return bmp;
}
public static void Main()
{
Console.WriteLine("Taking a screenshot now...");
TakeScreenshot("screenshot.bmp");
Console.WriteLine("\nDone! Press any key to exit...");
Console.ReadKey();
}
}
}
Side note: Many users have more than one monitor these days, so if you want to take a screenshot that captures all the screens, you can create a rectangle that encompasses all screens:
public static Bitmap TakeScreenshot(string filePath = null)
{
var rect = new Rectangle();
// Take a screenshot that includes all screens by
// creating a rectangle that captures all monitors
foreach (var screen in Screen.AllScreens)
{
var bounds = screen.Bounds;
var width = bounds.X + bounds.Width;
var height = bounds.Y + bounds.Height;
if (width > rect.Width) rect.Width = width;
if (height > rect.Height) rect.Height = height;
}
var bmp = new Bitmap(rect.Width, rect.Height);
using (var g = Graphics.FromImage(bmp))
{
g.CopyFromScreen(0, 0, 0, 0, rect.Size);
}
if (filePath != null) bmp.Save(filePath);
return bmp;
}