wpf下实现简单截图

1.实现一个图形转换工具类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using System.Drawing;
using System.Runtime.InteropServices;
using System.IO;
using System.Windows;

namespace Manager.com.longtie.util
{
    public class BitmapImageUtil
    { 
        [DllImport("gdi32")]
        static extern int DeleteObject(IntPtr o);
        private static MemoryStream globalMemoryStream = new System.IO.MemoryStream();
        public static BitmapSource getBitMapSourceFromSnapScreen()
        {
            Bitmap bitmap = GetScreenSnapshot();
            IntPtr intPtrl = bitmap.GetHbitmap();
            BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(intPtrl, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            DeleteObject(intPtrl);
            return bitmapSource;
        }
        public static BitmapSource getBitMapSourceFromBitmap(Bitmap bitmap)
        { 
            IntPtr intPtrl = bitmap.GetHbitmap();
            BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(intPtrl, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            DeleteObject(intPtrl);
            return bitmapSource;
        }
        public static BitmapImage getBitmapImageFromSnapScreen()
        {
            Bitmap bitmap = GetScreenSnapshot();
            bitmap.Save(globalMemoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
            byte[] bitmapBytes = globalMemoryStream.GetBuffer();  //byte[]   bytes=   ms.ToArray();  
            //ms.Close(); 
            bitmap.Dispose();
            // Init bitmap
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = new MemoryStream(bitmapBytes);
            bitmapImage.EndInit();
            return bitmapImage;
        }

        public static BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
        {
            BitmapImage bitmapImage = new BitmapImage();
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = ms;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();
                bitmapImage.Freeze();
            }

            return bitmapImage;
        }


        public static Bitmap GetScreenSnapshot()
        {
            System.Drawing.Rectangle rc = System.Windows.Forms.SystemInformation.VirtualScreen;
            var bitmap = new Bitmap(rc.Width, rc.Height);

            using (Graphics g = Graphics.FromImage(bitmap))
            {
                g.CopyFromScreen(rc.X, rc.Y, 0, 0, rc.Size, CopyPixelOperation.SourceCopy);
            }

            return bitmap;
        }
    }
}
  1. 点击按钮,调用弹出窗体的代码:
  DateTime dt = DateTime.Now;
  Bitmap bitMap = BitmapImageUtil.GetScreenSnapshot();
  BitmapImage bitmapImage = BitmapImageUtil.BitmapToBitmapImage(bitMap);

  Window7 win7 = new Window7(bitmapImage, bitMap);
  win7.ShowDialog();

  //image1.Source 
  ImageSource img = Clipboard.GetImage();
  image1.Width = img.Width;
  image1.Height = img.Height;
  image1.Source = img;

3.弹出窗体的xmal代码:

 <Window x:Class="Manager.Window7"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" WindowStyle="None" WindowState="Maximized"
        Title="Window7" Height="300" Width="300" MouseDoubleClick="Window_MouseDoubleClick">
    <Grid  Name="mainGrid"  MouseDown="Window_MouseDown" MouseMove="Window_MouseMove" MouseLeave="Window_MouseLeave" MouseUp="Window_MouseUp">

    </Grid>
</Window>

4.弹出窗体的cs代码

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.Shapes;
using Manager.com.longtie.util; 

namespace Manager
{
    /// <summary>
    /// Window7.xaml 的交互逻辑
    /// </summary>
    public partial class Window7 : Window
    {
        private BitmapImage GlobalBitmapImage;
        private System.Drawing.Bitmap GlobalBitmap;
        private bool DownFlag = false;
        private Point PreviousPoint;
        private Border globalBorder;
        public Window7(BitmapImage bitmapImage, System.Drawing.Bitmap bitMap)
        {
            InitializeComponent();  
            GlobalBitmap = bitMap;
            GlobalBitmapImage = bitmapImage;
            mainGrid.Background = new ImageBrush() { ImageSource = GlobalBitmapImage };

            globalBorder = new Border() { BorderBrush =  Brushes.Gray, BorderThickness = new Thickness(1) };
            mainGrid.Children.Add(globalBorder);
        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            DownFlag = true;
            PreviousPoint = e.GetPosition(mainGrid);
        }

        private void Window_MouseMove(object sender, MouseEventArgs e)
        { 
            if (DownFlag == true)
            {
                Point currentPoint = e.GetPosition(mainGrid);
                double left = Math.Min(PreviousPoint.X,currentPoint.X);
                double top = Math.Min(PreviousPoint.Y,currentPoint.Y);
                double width = Math.Abs(PreviousPoint.X-currentPoint.X);
                double height = Math.Abs(PreviousPoint.Y-currentPoint.Y);


                globalBorder.Margin = new Thickness(left,top,0,0);
                globalBorder.Width = width;
                globalBorder.Height = height;
                globalBorder.HorizontalAlignment = HorizontalAlignment.Left;
                globalBorder.VerticalAlignment = VerticalAlignment.Top;
            }
        }

        private void Window_MouseLeave(object sender, MouseEventArgs e)
        {
            DownFlag = false;

        }

        private void Window_MouseUp(object sender, MouseButtonEventArgs e)
        {
            DownFlag = false;
        }

        private void Window_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (DownFlag == true && globalBorder != null)
            {
                double left = globalBorder.Margin.Left;
                double top =  globalBorder.Margin.Top;
                double width = globalBorder.Width;
                double height =globalBorder.Height;
                double r_1 = left + width;
                double h_1 = top + height;

                Point currentPoint = e.GetPosition(mainGrid);
                if (currentPoint.X >= left && currentPoint.X <= r_1 && currentPoint.Y >= top && currentPoint.Y <= h_1)
                {
                    //图片保存
                    //this.Close();

                    System.Drawing.Image CatchedBmp = new System.Drawing.Bitmap((int)globalBorder.Width, (int)globalBorder.Height); 

                    System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(CatchedBmp); //创建图片画布 

                    ////目标范围
                    System.Drawing.Rectangle desiRectangle = new System.Drawing.Rectangle(0, 0, (int)globalBorder.Width, (int)globalBorder.Height);

                    ////源范围
                    System.Drawing.Rectangle sourceRectangle = new System.Drawing.Rectangle((int)left, (int)top, (int)globalBorder.Width, (int)globalBorder.Height);

                    g.DrawImage(GlobalBitmap, desiRectangle, sourceRectangle, System.Drawing.GraphicsUnit.Pixel);

                    //保存到剪贴板
                    System.Drawing.Bitmap map = (System.Drawing.Bitmap)CatchedBmp;
                    BitmapSource source = BitmapImageUtil.getBitMapSourceFromBitmap(map);
                    Clipboard.SetImage(source);
                    g.Dispose();
                    CatchedBmp.Dispose();
                    GlobalBitmap.Dispose();
                    this.Close(); 
                }
            }
        }
    }
}

5.思路整理:
(1) 通过winform中gdi+的写法来实现截图
(2) 因为wpf中使用的是 BitmapImage,而winform中使用的是Bitmap,因此存在图形对象的转换
(3) 多数代码来自网络
(4) 截图背景区可以通过填充四个矩形的方式实现

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
WPF 实现截图添加功能的步骤如下: 1. 首先需要在 WPF 窗口上添加一个按钮或者菜单项,用于触发截图功能。 2. 当用户点击按钮或者菜单项时,可以使用 WPF 内置的截图功能,将屏幕上的指定区域截取下来。 3. 接下来,可以在截图的基础上添加各种图形、文字、箭头、矩形等元素,用于标注和说明。 4. 最后,将修改后的截图保存到本地或者上传到服务器上。 以下是一个简单实现示例: XAML 代码: ```xml <Window x:Class="ScreenshotApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Screenshot App" Height="350" Width="525"> <Grid> <Button Content="Take screenshot" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="100" Click="OnTakeScreenshot"/> <Image x:Name="screenshotImage" HorizontalAlignment="Left" Margin="120,10,0,0" VerticalAlignment="Top" Stretch="None"/> </Grid> </Window> ``` C# 代码: ```csharp using System.Drawing; using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Forms; using System.Windows.Media.Imaging; namespace ScreenshotApp { public partial class MainWindow : Window { private Bitmap screenshot; public MainWindow() { InitializeComponent(); } private void OnTakeScreenshot(object sender, RoutedEventArgs e) { // 截取整个屏幕 screenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); using (Graphics g = Graphics.FromImage(screenshot)) { g.CopyFromScreen(0, 0, 0, 0, screenshot.Size); } // 显示截图 screenshotImage.Source = BitmapToImageSource(screenshot); } private void OnSaveScreenshot(object sender, RoutedEventArgs e) { if (screenshot != null) { // 保存截图 var dialog = new SaveFileDialog(); dialog.Filter = "PNG files (*.png)|*.png"; if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { screenshot.Save(dialog.FileName, System.Drawing.Imaging.ImageFormat.Png); } } } private void OnAddRectangle(object sender, RoutedEventArgs e) { if (screenshot != null) { // 添加矩形 using (Graphics g = Graphics.FromImage(screenshot)) { g.DrawRectangle(Pens.Red, new Rectangle(100, 100, 200, 100)); } screenshotImage.Source = BitmapToImageSource(screenshot); } } // 将 Bitmap 转换为 ImageSource private ImageSource BitmapToImageSource(Bitmap bitmap) { using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); stream.Position = 0; BitmapImage result = new BitmapImage(); result.BeginInit(); result.CacheOption = BitmapCacheOption.OnLoad; result.StreamSource = stream; result.EndInit(); return result; } } } } ``` 在上面的示例中,我们使用了 WPF 内置的截图功能 `CopyFromScreen` 来截取整个屏幕。然后我们可以在截图上添加各种图形,例如矩形,使用 `DrawRectangle` 方法实现。最后,我们将修改后的截图显示在 `Image` 控件中,并且可以保存到本地。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值