Screen.PrimaryScreen.Bounds.Width,Height,Size error

问题描述 投票:0回答:1

我正在尝试创建一个可获取整个屏幕截图的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
}

但是由于某种原因,我得到一个错误提示

名称“屏幕”在当前上下文中不存在

c# bitmap
1个回答
0
投票

但是由于某种原因,我收到一条错误消息,指出“名称'Screen'在当前上下文中不存在”

原因是Screen类属于System.Windows.Forms程序集,默认情况下在控制台应用程序中未引用该程序集。

要解决此问题,请在您的项目中添加对程序集的引用,然后在代码文件的顶部添加using System.Windows.Forms

添加参考:

  1. 在解决方案资源管理器中右键单击您的项目,然后选择“添加引用...”
  2. 在打开的“参考管理器”窗口中,导航到左侧的Assemblies -> Framework
  3. 向下滚动中间窗口并选中System.Windows.Forms旁边的框
  4. 单击“确定”

然后将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; }
© www.soinside.com 2019 - 2024. All rights reserved.