截图时出现 InvalidArgumentException

InvalidArgumentException when taking screenshot

每一秒,我都会使用以下代码捕获我的屏幕。前 40/50 次有效,之后我在代码的第一行和第三行得到一个 InvalidArgumentException

Bitmap bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics g = Graphics.FromImage(bmpScreenshot);
g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);
bmpScreen = bmpScreenshot;

可能您需要处理一些对象。

仅从显示的代码很难判断,但我的猜测是您没有正确处理对象并且 运行 内存不足。我确信 Graphics 对象应该被处理掉,当你用完它时,位图可能也需要被处理掉。根据错误捕获的设置方式,如果您吞下内存不足异常并继续运行,那么不适合可用内存的新对象将不会被实例化,它们的构造函数将 return 为 null。如果您随后将 null 传递给不想接收 null 的方法,则可能会导致 InvalidArgumentException

尝试将您的 Disposable 对象包装在 using 语句中。我能够使用以下代码重现您的问题:

public static void Main()
{
    var i = 1;

    while (true)
    {
        var screenSize = Screen.PrimaryScreen.Bounds.Size;

        try
        {                
            var bmpScreenshot = new Bitmap(screenSize.Width, screenSize.Height);
            var g = Graphics.FromImage(bmpScreenshot);
            g.CopyFromScreen(0, 0, 0, 0, screenSize);
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception ignored: {0}", e.Message);
        }
        finally
        {
            Console.WriteLine("Iteration #{0}", i++);
            Thread.Sleep(TimeSpan.FromSeconds(1));
        }
    }
}

通过用 using 语句包装一次性用品,问题没有再次发生:

public static void Main()
{
    var i = 1;

    while (true)
    {
        var screenSize = Screen.PrimaryScreen.Bounds.Size;

        try
        {                
            using (var bmpScreenshot = new Bitmap(screenSize.Width, screenSize.Height))
            using (var g = Graphics.FromImage(bmpScreenshot))
            {
                g.CopyFromScreen(0, 0, 0, 0, screenSize);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception ignored: {0}", e.Message);
        }
        finally
        {
            Console.WriteLine("Iteration #{0}", i++);
            Thread.Sleep(TimeSpan.FromSeconds(1));
        }
    }
}