C # - снимок экрана на основе таймера - PullRequest
4 голосов
/ 31 марта 2010

Я пытаюсь создать приложение WinForms, которое делает снимок экрана с заданным интервалом. Я думаю, что мой код правильный, но когда я пытаюсь его запустить, я получаю сообщение об ошибке «System.Runtime.InteropServices.ExternalException не обработано, в 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 голосов
/ 31 марта 2010

Вам нужно сохранить с реальным именем файла, например так:

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

Ваш код передается по пути, который не содержит имени файла. Кроме того, убедитесь, что Environment.GetFolderPath (...) возвращает путь без «\» в конце, иначе вы получите «\\» на своем пути.

...