wpf 控件截屏

原文: wpf 控件截屏

        /// <summary>
        /// 保存截图
        /// </summary>
        /// <param name="ui">控件名称</param>
        /// <param name="filename">图片文件名</param>
        public void SaveFrameworkElementToImage(FrameworkElement ui, string filename)
        {
            try
            {
                System.IO.FileStream ms = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                System.Windows.Media.Imaging.RenderTargetBitmap bmp = new System.Windows.Media.Imaging.RenderTargetBitmap((int)ui.ActualWidth, (int)ui.ActualHeight, 96d, 96d, System.Windows.Media.PixelFormats.Pbgra32);
                bmp.Render(ui);
                System.Windows.Media.Imaging.JpegBitmapEncoder encoder = new System.Windows.Media.Imaging.JpegBitmapEncoder();
                encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp));
                encoder.Save(ms);
                ms.Close();

                File.Copy(filename, "D:\\pictures\\" + filename, true);
            }
            catch (Exception ex)
            {
                //记录异常
            }
        }

测试代码:

            string pattern = "-|:";
            Regex regex = new Regex(pattern);
            string s = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff").Replace(" ", "");
            string path = regex.Replace(s, "")+".jpg";
            SaveFrameworkElementToImage(picShow, path);//picShow为控件名称

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/10275473.html