views:

109

answers:

1

Hello everybody. I'm trying to create a WinForms app that takes a screenshot on a set interval. I think my code is correct, but when I try to run it, I get the error message "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();
    }

The line that's giving my trouble is:

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

Any ideas about what is going wrong? Thanks in advance.

+2  A: 

You need to save with an actual file name, like so:

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

Your code is passing in a path that does not include a file name. Also, check to make sure that Environment.GetFolderPath(...) returns a path without a "\" on the end, or you'll end up with a "\\" in your path.

MusiGenesis
That's weird - I had to type 3 back-slashes in order to get 2 to show up.
MusiGenesis