WPF—截屏

作者:追风剑情 发布于:2019-8-20 17:01 分类:C#

示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;//INotifyPropertyChanged
using System.Threading.Tasks;

namespace WpfTest
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //对窗口截屏
            System.Drawing.Bitmap bmp = GetWindowSnapshot();
            SaveWindowSnapshot("F:\\snapshot.png", bmp);
        }

        /// <summary>
        /// 对窗口截屏
        /// </summary>
        /// <param name="padding">相对窗口的内边矩</param>
        /// <returns></returns>
        public System.Drawing.Bitmap GetWindowSnapshot(int left = 0, int top = 0, int right = 0, int bottom = 0)
        {
            //窗口本地坐标
            Point ptLeftUp = new Point(left, top);
            Point ptRightDown = new Point(this.ActualWidth - right, this.ActualHeight - bottom);
            //本地坐标转屏幕坐标
            ptLeftUp = this.PointToScreen(ptLeftUp);
            ptRightDown = this.PointToScreen(ptRightDown);
            //窗口在屏幕上的宽高
            double width = ptRightDown.X - ptLeftUp.X;
            double height = ptRightDown.Y - ptLeftUp.Y;
            System.Drawing.Size size = new System.Drawing.Size((int)width, (int)height);

            try
            {
                //System.Drawing.Rectangle rc = System.Windows.Forms.SystemInformation.VirtualScreen;
                var bitmap = new System.Drawing.Bitmap((int)width, (int)height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                using (System.Drawing.Graphics memoryGrahics = System.Drawing.Graphics.FromImage(bitmap))
                {
                    memoryGrahics.CopyFromScreen((int)ptLeftUp.X, (int)ptLeftUp.Y, 0, 0, size, System.Drawing.CopyPixelOperation.SourceCopy);
                }
                return bitmap;
            }
            catch (Exception)
            {

            }
            return null;
        }

        /// <summary>
        /// 保存截图
        /// </summary>
        /// <param name="filePath"></param>
        public void SaveWindowSnapshot(string filePath, System.Drawing.Bitmap bmp)
        {
            if (bmp == null)
                return;
            bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
        }
    }
}

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号