第一种方法,简单粗暴,但是有个问题,有些控件如果用了winform里的控件来承载,截图显示不了其中的内容,比如视频图像。
System.Windows.Media.Imaging.RenderTargetBitmap targetBitmap = new System.Windows.Media.Imaging.RenderTargetBitmap((int)this.MulPlayerController.ActualWidth, (int)this.MulPlayerController.ActualHeight, 96d, 96d, System.Windows.Media.PixelFormats.Default);
targetBitmap.Render(this.gridChilren);
System.Windows.Media.Imaging.PngBitmapEncoder saveEncoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
saveEncoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(targetBitmap));
string tempFile = System.IO.Path.GetTempFileName() + ".png";
System.IO.FileStream fs = System.IO.File.Open(tempFile, System.IO.FileMode.OpenOrCreate);
saveEncoder.Save(fs);
fs.Close();
第二种方法,思路是先将整个屏幕截取下来,如何获得你想要截图区域的坐标和宽高,然后将屏幕中对应的位置区域保存为图片就可以了。
//获得当前屏幕的分辨率
Screen scr = Screen.PrimaryScreen;
System.Drawing.Rectangle rc = scr.Bounds;
int iWidth = rc.Width;
int iHeight = rc.Height;
//创建一个和屏幕一样大的Bitmap
System.Drawing.Image myImage = new System.Drawing.Bitmap((int)this.MulPlayerController.pnlMain.ActualWidth, (int)this.MulPlayerController.pnlMain.ActualHeight);
//从一个继承自Image类的对象中创建Graphics对象
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(myImage);
Point controlPoint = new Point(0, 0);
controlPoint = this.MulPlayerController.pnlMain.PointToScreen(controlPoint);//获取控件相对于屏幕的位置
//抓屏并拷贝到myimage里
g.CopyFromScreen(new System.Drawing.Point((int)controlPoint.X, (int)controlPoint.Y), new System.Drawing.Point(0, 0),
new System.Drawing.Size((int)this.MulPlayerController.pnlMain.ActualWidth, (int)this.MulPlayerController.pnlMain.ActualHeight));
//保存为文件
myImage.Save("1.jpg");
string tempFileImg = "1.jpg";