我正在尝试创建一个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);
关于出了什么问题的任何想法?提前谢谢。
答案 0 :(得分:3)
您需要使用实际文件名保存,如下所示:
bmpScreenshot.Save(Environment.GetFolderPath
(Environment.SpecialFolder.DesktopDirectory)
+ @"\ScreenCaptures\newfile.png", ImageFormat.Png);
您的代码传递的路径不包含文件名。另外,请检查以确保Environment.GetFolderPath(...)返回末尾没有“\”的路径,否则您的路径中将以“\\”结尾。