我正在尝试创建一个可获取整个屏幕截图的ac#控制台应用程序,我知道在SO上已经问过很多遍了,但是我有一个问题,就是我找不到答案至。
这是我的代码:
Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
using (Graphics g = Graphics.FromImage(bmp))
{
g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);
bmp.Save("screenshot.png"); // saves the image
}
但是由于某种原因,我得到一个错误提示
名称“屏幕”在当前上下文中不存在
但是由于某种原因,我收到一条错误消息,指出“名称'Screen'在当前上下文中不存在”
原因是Screen
类属于System.Windows.Forms
程序集,默认情况下在控制台应用程序中未引用该程序集。
要解决此问题,请在您的项目中添加对程序集的引用,然后在代码文件的顶部添加using System.Windows.Forms
。
添加参考:
Assemblies -> Framework
System.Windows.Forms
旁边的框然后将using
语句添加到您的代码文件中,类似于基于您的代码的此示例:
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();
}
}
}
旁注:如今,许多用户拥有不止一台显示器,因此,如果要截取捕获[[all屏幕的屏幕截图,则可以创建一个包含所有屏幕的矩形:
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;
}