WPF 实现屏幕截图

138 阅读5分钟

源码地址

gitee.com/LiuShuiRuoB…

实现功能

实现基本的截屏窗体

鼠标随意选择截图区域

鼠标抬起时弹出按钮区

快捷键Ctrl+Alt+z触发截屏

ESC取消截屏

实现Save按钮,将截图保存在系统剪切板

实现Load按钮,将截图保存到本地磁盘

要实现类似QQ和微信的截图功能,思路大概是这样的,触发截图时将调用Windows的API将当前屏幕的图像内容转换成Bitmap的格式,并将其放置在截屏窗体的Canvas的控件中,然后检测鼠标按下和抬起的位置,并依据此绘制想要的截图矩形区域,当鼠标抬起时弹出按键操作区,并实现保存截图的功能。

ScreenWindow的思路以及控件构成

截屏窗体主要由两个部分组成,一个是图像选择区,一个是按钮区,其中当触发截屏时随着鼠标的移动会绘制图像选区,当鼠标按键抬起时才显示按钮区。

首先ScreenWindow要设置为最大化、无边框、背景透明,这样在窗体弹出时就可只显示图像载体控件的内容了

WindowState="Maximized" WindowStyle="None" AllowsTransparency="True" Background="Transparent"

要考虑截屏内容的载体控件,因为截屏内容后期可能也会在上面绘制图形,所以考虑将其放在Canvas控件中,而为了动态实现鼠标移动时实时绘制图形的选择区域,可以考虑使用Rectangle加Border来实现,具体效果演示如下:

在Canvas控件中放入left、right、top、bottom 4个矩形,然后根据鼠标按下抬起的位置绘制border,这个borde的区域即为选中的截图区域,同时鼠标移动时来不断地计算left、right、top、bottom 4个矩形和border在Canvas中的位置,并且动态绘制,从而实现截图区域的动态绘制。

按钮区的实现,按钮区在开始的时候需要隐藏,当鼠标抬起时才显示出来,按钮区的容器控件可以选择WrapPanel,使用Canvas.Bottom="0" 和 Canvas.Right="0" 将其设置到Canvas的右下角,在ScreenWindow弹出时默认隐藏,当鼠标抬起时再将其显示出来,可以通过设置Visibility属性实现。

其在Canvas中的位置处理代码如下:

private void Window_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    if (!IsMouseUp)
    {
        WrapPanel_Btns.Visibility = Visibility.Visible;
        
        //当所选的截图区域不大时,按钮区直接在其下方显示
        if (Rect_RealScreen.Y + Rect_RealScreen.Height + this.WrapPanel_Btns.ActualHeight < SystemParameters.PrimaryScreenHeight)
        {
            Canvas.SetRight(this.WrapPanel_Btns, Rectangle_Right.Width);
            Canvas.SetBottom(this.WrapPanel_Btns, Rectangle_Bottom.Height - this.WrapPanel_Btns.ActualHeight - 4);
        }
        else //当鼠标选择区域大到一定程度时,设置按钮选择区的位置到选择区域内左上角
        {
            Canvas.SetLeft(this.WrapPanel_Btns, Rect_RealScreen.X + 4);
            Canvas.SetTop(this.WrapPanel_Btns, Rect_RealScreen.Y + 4);
        }

        IsMouseUp = true;
    }
}

如何利用WIndows API来实现当前屏幕的截图

在触发截图功能时需要先将当前屏幕截屏,并存储在Bitmap中,以供后面使用,可以先创建一个屏幕大小的Bitmap,然后利用此Bitmap创建一个Graphics对象实例,使用Graphics的CopyFromScreen()函数将当前屏幕截图,并保存到之前创建的Bitmap中。

具体代码如下:

/// <summary>
/// 获取当前截屏
/// </summary>
/// <returns></returns>
public static Bitmap CaptureCurrentScreen()
{
    //创建与屏幕大小相同的位图对象
    var bmpScreen = new Bitmap((int)SystemParameters.PrimaryScreenWidth, (int)SystemParameters.PrimaryScreenHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

    //使用位图对象来创建Graphics的对象
    using (Graphics g = Graphics.FromImage(bmpScreen))
    {
        g.SmoothingMode = SmoothingMode.AntiAlias;   //设置平滑模式,抗锯齿
        g.CompositingQuality = CompositingQuality.HighQuality;  //设置合成质量
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;     //设置插值模式
        g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;   //设置文本呈现的质量
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;    //设置呈现期间,像素偏移的方式

        //利用CopyFromScreen将当前屏幕截图并将内容存储在bmpScreen的位图中
        g.CopyFromScreen(0, 0, 0, 0, bmpScreen.Size, CopyPixelOperation.SourceCopy);
    }

    return bmpScreen;
}

根据鼠标移动动态绘制截图区域

如果所示当鼠标按下移动时可以根据起始点,以及当前点实时绘制Border矩形,同时可计算出Left、Right、Top、Bottom 4个矩形的位置,通过Canvas不断设置各部分的位置,4个矩形的遮挡的地方实现背景虚化,而Border选择区真实显示

private void MoveAllRectangle(System.Windows.Point current)
{
    PointEnd = current;
    Rect_RealScreen = new Rect(PointStart, PointEnd);

    //设置left矩形
    this.Rectangle_Left.Width = Rect_RealScreen.X;
    this.Rectangle_Left.Height = Canvas_ScreenCut.Height;
    Canvas.SetLeft(this.Rectangle_Left, 0);
    Canvas.SetTop(this.Rectangle_Left, 0);

    //设置Top矩形
    this.Rectangle_Top.Width = Rect_RealScreen.Width;
    double h = 0.0;
    if (current.Y < PointStart.Y)
        h = current.Y;
    else
        h = current.Y - Rect_RealScreen.Height;
    this.Rectangle_Top.Height = h;
    Canvas.SetLeft(this.Rectangle_Top, this.Rectangle_Left.Width);
    Canvas.SetTop(this.Rectangle_Top, 0);

    //设置right矩形
    this.Rectangle_Right.Width = Canvas_ScreenCut.Width - (Rect_RealScreen.Width + this.Rectangle_Left.Width);
    this.Rectangle_Right.Height = Canvas_ScreenCut.Height;
    Canvas.SetLeft(this.Rectangle_Right, this.Rectangle_Left.Width + Rect_RealScreen.Width);
    Canvas.SetTop(this.Rectangle_Right, 0);

    //设置bottom矩形
    this.Rectangle_Bottom.Width = Rect_RealScreen.Width;
    this.Rectangle_Bottom.Height = Canvas_ScreenCut.Height - (Rect_RealScreen.Height + this.Rectangle_Top.Height);
    Canvas.SetLeft(this.Rectangle_Bottom, this.Rectangle_Left.Width);
    Canvas.SetTop(this.Rectangle_Bottom, Rect_RealScreen.Height + this.Rectangle_Top.Height);

    //设置border选择的图形区
    this.Border_ScreenCut.Height = Rect_RealScreen.Height;
    this.Border_ScreenCut.Width = Rect_RealScreen.Width;
    Canvas.SetLeft(this.Border_ScreenCut, Rect_RealScreen.X);
    Canvas.SetTop(this.Border_ScreenCut, Rect_RealScreen.Y);
}

按钮区的逻辑实现

Cancel 按钮,直接关闭窗体来取消截屏

Save按钮,将截屏内容保存到系统的额剪切板中

private void Btn_Save_Click(object sender, RoutedEventArgs e)
{
    BitmapFrame bitmapFrame = BitmapFrame.Create(ImageProcessHelper.CutBitmap(Canvas_ScreenCut, Rect_RealScreen));
    Clipboard.SetImage(bitmapFrame);
    Close();
}

Load 按钮,保存并下载截图区域到指定文件

private void Btn_Save_Click(object sender, RoutedEventArgs e)
{
    SaveFileDialog dlg = new SaveFileDialog();
    dlg.FileName = $"ScreenCut_{DateTime.Now.ToString("yyyyMMddHHmmss")}.png";
    dlg.DefaultExt = ".png";
    dlg.Filter = "image file|*.png";

    if (dlg.ShowDialog() == true)
    {
        BitmapEncoder pngEncoder = new PngBitmapEncoder();
        pngEncoder.Frames.Add(BitmapFrame.Create(CutBitmap()));
        using (var fs = File.OpenWrite(dlg.FileName))
        {
            pngEncoder.Save(fs);
        }
    }
    Close();
}

CutBitmap()函数的实现

由于整个屏幕截图已经放置到了Canvas控件中,所以可以使用RenderTargetBitmap构造一个对象实例,将Visual对象转换成位图,

然后利用CroppedBitmap,从整个截屏中剪裁出 选中的区域,并转换成Bitmap来进行存储。

/// <summary>
/// 截图实现
/// </summary>
/// <param name="frameworkElement">带有绘图内容的控件元素</param>
/// <param name="rect">要截图的区域</param>
/// <returns></returns>
public static CroppedBitmap CutBitmap(FrameworkElement frameworkElement, Rect rect)
{
    //将Visual 对象转换为位图
    var renderTargetBitmap = new RenderTargetBitmap((int)frameworkElement.Width, (int)frameworkElement.Height, 96d, 96d, PixelFormats.Default);
    renderTargetBitmap.Render(frameworkElement);

    //按照Border绘制的rect剪裁Bitmap(9 和 5 都是为了去掉边框)
    return new CroppedBitmap(renderTargetBitmap, new Int32Rect((int)rect.X + 9, (int)rect.Y + 9, (int)rect.Width - 5, (int)rect.Height - 5));
}

最后

如果你觉得这篇文章对你有帮助,不妨点个赞支持一下!你的支持是我继续分享知识的动力。如果有任何疑问或需要进一步的帮助,欢迎随时留言。

也可以加入微信公众号 [DotNet技术匠] 社区,与其他热爱技术的同行一起交流心得,共同成长!

优秀是一种习惯,欢迎大家留言学习!

作者:流水若冰

出处:cnblogs.com/liushuiruobing/p/16262024.html

声明:网络内容,仅供学习,尊重版权,侵权速删,歉意致谢!