C# - 根据定时器截取屏幕截图

4

我正在尝试创建一个WinForms应用程序,以在一定时间间隔内截取屏幕截图。我认为我的代码是正确的,但当我尝试运行它时,我会收到错误消息“System.Runtime.InteropServices.ExternalException was unhandled, A generic error occurred in GDI+。”

    System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
    Thread th;
    private static Bitmap bmpScreenshot;
    private static Graphics gfxScreenshot;

    void TakeScreenShot()
    {
        bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
        gfxScreenshot = Graphics.FromImage(bmpScreenshot);
        gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
        bmpScreenshot.Save(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\ScreenCaptures", ImageFormat.Png);
        th.Abort();
    }

    void StartThread(object sender, EventArgs e)
    {
        th = new Thread(new ThreadStart(TakeScreenShot));
        th.Start();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\ScreenCaptures");
        t.Interval = 500;
        t.Tick += new EventHandler(StartThread);
        t.Start();
    }

这个让我困扰的代码行是:
bmpScreenshot.Save(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\ScreenCaptures", ImageFormat.Png);

有什么想法是出了什么问题吗?提前感谢。
1个回答

3

您需要使用实际文件名进行保存,如下所示:

bmpScreenshot.Save(Environment.GetFolderPath
    (Environment.SpecialFolder.DesktopDirectory) 
    + @"\ScreenCaptures\newfile.png", ImageFormat.Png);

您的代码传递了不包含文件名的路径。此外,请确保Environment.GetFolderPath(...)返回的路径结尾没有"\",否则您最终的路径中将会出现"\\\"。


很奇怪 - 我必须输入3个反斜杠才能显示2个。 - MusiGenesis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接