在C#中获取屏幕截图时出现StackOverflowException

时间:2020-01-19 19:33:26

标签: c# winforms stack-overflow

我有很多方法可以截取屏幕截图。在那:

private Bitmap GetPlayedScreen()
{
    var rect = new Rectangle(Location.X, Location.Y, Width, Height);
    var img = new Bitmap(rect.Width, rect.Height, PixelFormat.Format64bppArgb);
    var GFX = Graphics.FromImage(img);
    GFX.CopyFromScreen(rect.Left, rect.Top, 0, 0, Size);
    return img;
}

我将这种方法与如下代码一起使用:

GetPlayedScreen().Save(/*file_path_to_be_saved*/, ImageFormat.Jpeg);
labelFileName.Text = @"● " + file_name;
_counter += 1;

当此过程重复数百次时,我得到StackOverflowException错误。由于我无法解决此错误,因此无法捕获并结束该过程。

这是我的完整代码:

public partial class PlayedScreen : Form
{
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
    private int _counter { get; set; } = 1;
    public PlayedScreen()
    {
        InitializeComponent();
        RegisterHotKey(Handle, 0, 0, Keys.F5.GetHashCode());
    }
    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);

        if (m.Msg == 0x0312)
        {
            if (_counter < 1300)
            {
                var file_name = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fff") + ".jpg";
                GetPlayedScreen().Save("D:\\Test\\" + file_name, ImageFormat.Jpeg);
                label1.Text = @"● " + file_name;

                SendKeys.SendWait("{F5}");
                _counter += 1;
            }
        }
    }
    private Bitmap GetPlayedScreen()
    {
        var rect = new Rectangle(Location.X, Location.Y, Width, Height);
        var img = new Bitmap(rect.Width, rect.Height, PixelFormat.Format64bppArgb);
        var GFX = Graphics.FromImage(img);
        GFX.CopyFromScreen(rect.Left, rect.Top, 0, 0, Size);
        return img;
    }
}

当我按F5键时,我希望GetPlayedScreen方法重复1300次,但是它在大约500次重复中给出了StackOverflowException错误。

1 个答案:

答案 0 :(得分:2)

在消息处理程序中避免使用SendMessage。

K.int_shape(y)

(None, 1, 2352)