WPF:截取屏幕截图并保存
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34837286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF: Take a screenshot and save it
提问by Raya
I'm new to WPF applications and I've tried looking around to see if I could find something that works for this, but so far nothing I've found works (I guess it's because most of it is outdated). I want to take a screenshot of the entire desktop (i.e. all monitors) and save it as a .jpgto a specific folder with the time and date as the file name when I click the screenshot button. I was able to achieve this in my Windows Forms application, but haven't been able to do so with my WPF application.
我是 WPF 应用程序的新手,我试着环顾四周,看看我是否能找到适合这个的东西,但到目前为止我没有发现任何有用的东西(我想这是因为大部分已经过时了)。我想截取整个桌面(即所有显示器)的屏幕截图并将其保存.jpg到特定文件夹中,当我单击屏幕截图按钮时,将时间和日期作为文件名。我能够在我的 Windows 窗体应用程序中实现这一点,但我的 WPF 应用程序无法做到这一点。
This is the code that I used for my Windows Forms application.
这是我用于 Windows 窗体应用程序的代码。
int screenLeft = SystemInformation.VirtualScreen.Left;
int screenTop = SystemInformation.VirtualScreen.Top;
int screenWidth = SystemInformation.VirtualScreen.Width;
int screenHeight = SystemInformation.VirtualScreen.Height;
using (Bitmap bmp = new Bitmap(screenWidth, screenHeight))
{
using (Graphics g = Graphics.FromImage(bmp))
{
String filename = "ScreenCapture-" + DateTime.Now.ToString("ddMMyyyy-hhmmss") + ".png";
Opacity = .0;
g.CopyFromScreen(screenLeft, screenTop, 0, 0, bmp.Size);
bmp.Save("C:\ScreenShots\" + filename);
Opacity = 1;
}
}
Any help would be appreciated.
任何帮助,将不胜感激。
回答by fillobotto
In WPF project, you have to manually add reference to System.Drawing.dlllibrary. To do so, Project > Add reference > Assembly tab (Framework) > check the desired library.
在 WPF 项目中,您必须手动添加对System.Drawing.dll库的引用。为此,项目 > 添加引用 > 装配选项卡(框架)> 检查所需的库。
Moreover your code needs just a bit of tweaking, but the idea it's correct.
此外,您的代码只需要一点点调整,但它的想法是正确的。
double screenLeft = SystemParameters.VirtualScreenLeft;
double screenTop = SystemParameters.VirtualScreenTop;
double screenWidth = SystemParameters.VirtualScreenWidth;
double screenHeight = SystemParameters.VirtualScreenHeight;
using (Bitmap bmp = new Bitmap((int)screenWidth,
(int)screenHeight))
{
using (Graphics g = Graphics.FromImage(bmp))
{
String filename = "ScreenCapture-" + DateTime.Now.ToString("ddMMyyyy-hhmmss") + ".png";
Opacity = .0;
g.CopyFromScreen((int)screenLeft, (int)screenTop, 0, 0, bmp.Size);
bmp.Save("C:\Screenshots\" + filename);
Opacity = 1;
}
}

