C # - Timer Based Screenshot

I am trying to create a WinForms application that takes a screenshot at a given interval. I think my code is correct, but when I try to run it, I get the error "System.Runtime.InteropServices.ExternalException was unhandled, a general 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();
    }

The line that causes my problem:

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

Any ideas on what's going wrong? Thanks in advance.

+3
source share
1 answer

You need to save the actual file name, for example:

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

, . , , Environment.GetFolderPath(...) "\" , "\\" .

+3

Source: https://habr.com/ru/post/1739237/


All Articles