最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

WPF仿微信實現(xiàn)截圖功能的方法詳解

 更新時間:2022年07月29日 09:02:23   作者:驚鏵  
這篇文章主要介紹了如何利用WPF實現(xiàn)截圖功能(仿微信),文中的示例代碼講解詳細,對我們學習或工作有一定幫助,需要的可以參考一下

每日一笑

肚子疼,去廁所排便,結(jié)果什么都沒拉出來。看著自己坐在馬桶上痛苦又努力卻一無所獲的樣子,仿佛看到了自己平凡的一生。 

前言 

有小伙伴需要在軟件反饋窗體增加截圖功能需求,所以今天來實現(xiàn)一個仿微信的截圖。

效果預覽(更多效果請下載源碼體驗)

一、ScreenCut.cs 代碼如下

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WPFDevelopers.Controls
{
    [TemplatePart(Name = CanvasTemplateName, Type = typeof(Canvas))]
    [TemplatePart(Name = RectangleLeftTemplateName, Type = typeof(Rectangle))]
    [TemplatePart(Name = RectangleTopTemplateName, Type = typeof(Rectangle))]
    [TemplatePart(Name = RectangleRightTemplateName, Type = typeof(Rectangle))]
    [TemplatePart(Name = RectangleBottomTemplateName, Type = typeof(Rectangle))]
    [TemplatePart(Name = BorderTemplateName, Type = typeof(Border))]
    [TemplatePart(Name = WrapPanelTemplateName, Type = typeof(WrapPanel))]
    [TemplatePart(Name = ButtonSaveTemplateName, Type = typeof(Button))]
    [TemplatePart(Name = ButtonCancelTemplateName, Type = typeof(Button))]
    [TemplatePart(Name = ButtonCompleteTemplateName, Type = typeof(Button))]

    public class ScreenCut : Window
    {
        private const string CanvasTemplateName = "PART_Canvas";
        private const string RectangleLeftTemplateName = "PART_RectangleLeft";
        private const string RectangleTopTemplateName = "PART_RectangleTop";
        private const string RectangleRightTemplateName = "PART_RectangleRight";
        private const string RectangleBottomTemplateName = "PART_RectangleBottom";
        private const string BorderTemplateName = "PART_Border";
        private const string WrapPanelTemplateName = "PART_WrapPanel";
        private const string ButtonSaveTemplateName = "PART_ButtonSave";
        private const string ButtonCancelTemplateName = "PART_ButtonCancel";
        private const string ButtonCompleteTemplateName = "PART_ButtonComplete";

        private Canvas _canvas;
        private Rectangle _rectangleLeft, _rectangleTop, _rectangleRight, _rectangleBottom;
        private Border _border;
        private WrapPanel _wrapPanel;
        private Button _buttonSave,_buttonCancel, _buttonComplete;
        private Rect rect;
        private Point pointStart, pointEnd;
        private bool isMouseUp = false;

        static ScreenCut()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(ScreenCut), new FrameworkPropertyMetadata(typeof(ScreenCut)));
        }
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            _canvas = GetTemplateChild(CanvasTemplateName) as Canvas;
            _rectangleLeft = GetTemplateChild(RectangleLeftTemplateName) as Rectangle;
            _rectangleTop = GetTemplateChild(RectangleTopTemplateName) as Rectangle;
            _rectangleRight = GetTemplateChild(RectangleRightTemplateName) as Rectangle;
            _rectangleBottom = GetTemplateChild(RectangleBottomTemplateName) as Rectangle;
            _border = GetTemplateChild(BorderTemplateName) as Border;
            _wrapPanel = GetTemplateChild(WrapPanelTemplateName) as WrapPanel;
            _buttonSave = GetTemplateChild(ButtonSaveTemplateName) as Button;
            if (_buttonSave != null)
                _buttonSave.Click += _buttonSave_Click;
            _buttonCancel = GetTemplateChild(ButtonCancelTemplateName) as Button;
            if (_buttonCancel != null)
                _buttonCancel.Click += _buttonCancel_Click;
            _buttonComplete = GetTemplateChild(ButtonCompleteTemplateName) as Button;
            if (_buttonComplete != null)
                _buttonComplete.Click += _buttonComplete_Click;
            this._canvas.Background = new ImageBrush(ChangeBitmapToImageSource(CaptureScreen()));
            _rectangleLeft.Width = _canvas.Width;
            _rectangleLeft.Height = _canvas.Height;
        }

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

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

        private void _buttonComplete_Click(object sender, RoutedEventArgs e)
        {
           
            Clipboard.SetImage(CutBitmap());
            Close();
        }
        CroppedBitmap CutBitmap()
        {
            var renderTargetBitmap = new RenderTargetBitmap((int)_canvas.Width,
  (int)_canvas.Height, 96d, 96d, System.Windows.Media.PixelFormats.Default);
            renderTargetBitmap.Render(_canvas);
            return  new CroppedBitmap(renderTargetBitmap, new Int32Rect((int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height));
        }
        private void _buttonCancel_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
                Close();
        }

        protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            if (!isMouseUp)
            {
                _wrapPanel.Visibility = Visibility.Hidden;
                pointStart = e.GetPosition(_canvas);
                pointEnd = pointStart;
                rect = new Rect(pointStart, pointEnd);
            }

        }
        protected override void OnPreviewMouseMove(MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed && !isMouseUp)
            {
                var current = e.GetPosition(_canvas);
                MoveAllRectangle(current);
            }
        }
        protected override void OnPreviewMouseLeftButtonUp(MouseButtonEventArgs e)
        {
            if (!isMouseUp)
            {
                _wrapPanel.Visibility = Visibility.Visible;
                Canvas.SetLeft(this._wrapPanel, rect.X + rect.Width - this._wrapPanel.ActualWidth);
                Canvas.SetTop(this._wrapPanel, rect.Y + rect.Height + 4);
                isMouseUp = true;
            }
        }

        void MoveAllRectangle(Point current)
        {
            pointEnd = current;
            rect = new Rect(pointStart, pointEnd);
            this._rectangleLeft.Width = rect.X;
            this._rectangleLeft.Height = _canvas.Height;

            Canvas.SetLeft(this._rectangleTop, this._rectangleLeft.Width);
            this._rectangleTop.Width = rect.Width;
            double h = 0.0;
            if (current.Y < pointStart.Y)
                h = current.Y;
            else
                h = current.Y - rect.Height;
            this._rectangleTop.Height = h;

            Canvas.SetLeft(this._rectangleRight, this._rectangleLeft.Width + rect.Width);
            this._rectangleRight.Width = _canvas.Width - (rect.Width + this._rectangleLeft.Width);
            this._rectangleRight.Height = _canvas.Height;

            Canvas.SetLeft(this._rectangleBottom, this._rectangleLeft.Width);
            Canvas.SetTop(this._rectangleBottom, rect.Height + this._rectangleTop.Height);
            this._rectangleBottom.Width = rect.Width;
            this._rectangleBottom.Height = _canvas.Height - (rect.Height + this._rectangleTop.Height);

            this._border.Height = rect.Height;
            this._border.Width = rect.Width;
            Canvas.SetLeft(this._border, rect.X);
            Canvas.SetTop(this._border, rect.Y);
        }
       
        System.Drawing.Bitmap CaptureScreen()
        {
            var bmpCaptured = new System.Drawing.Bitmap((int)SystemParameters.PrimaryScreenWidth, (int)SystemParameters.PrimaryScreenHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmpCaptured))
            {
                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;

                g.CopyFromScreen(0, 0, 0, 0, bmpCaptured.Size, System.Drawing.CopyPixelOperation.SourceCopy);
            }
            return bmpCaptured;
        }

        [System.Runtime.InteropServices.DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);
        ImageSource ChangeBitmapToImageSource(System.Drawing.Bitmap bitmap)
        {
            IntPtr hBitmap = bitmap.GetHbitmap();
            ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());

            if (!DeleteObject(hBitmap))
            {
                throw new System.ComponentModel.Win32Exception();
            }
            return wpfBitmap;
        }
    }
}

二、ScreenCut.xaml 代碼如下 

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:controls="clr-namespace:WPFDevelopers.Controls">
    
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Basic/ControlBasic.xaml"/>
        <ResourceDictionary Source="../Styles/Styles.Buttons.xaml"/>
    </ResourceDictionary.MergedDictionaries>

    <Style x:Key="RectangleStyle" TargetType="{x:Type Rectangle}">
        <Setter Property="Fill" Value="{StaticResource BlackSolidColorBrush}"/>
        <Setter Property="Opacity" Value=".5"/>
</Style>
    
    <Style TargetType="{x:Type controls:ScreenCut}" BasedOn="{StaticResource ControlBasicStyle}">
        <Setter Property="WindowState" Value="Maximized"/>
        <Setter Property="WindowStyle" Value="None"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type controls:ScreenCut}">
                    <Canvas x:Name="PART_Canvas"
            Width="{Binding Source={x:Static SystemParameters.PrimaryScreenWidth}}"
            Height="{Binding Source={x:Static SystemParameters.PrimaryScreenHeight}}">
                        <Rectangle x:Name="PART_RectangleLeft" Style="{StaticResource RectangleStyle}"/>
                        <Rectangle x:Name="PART_RectangleTop" Style="{StaticResource RectangleStyle}"/>
                        <Rectangle x:Name="PART_RectangleRight" Style="{StaticResource RectangleStyle}"/>
                        <Rectangle x:Name="PART_RectangleBottom" Style="{StaticResource RectangleStyle}"/>
                        <Border x:Name="PART_Border" BorderBrush="{StaticResource SuccessPressedSolidColorBrush}" 
                                BorderThickness="1"/>
                        <WrapPanel x:Name="PART_WrapPanel" 
                                   Visibility="Hidden" Panel.ZIndex="99"
                                   Height="38" Background="{StaticResource WhiteSolidColorBrush}"
                                   VerticalAlignment="Center">
                            <Button x:Name="PART_ButtonSave" Style="{StaticResource PathButton}"
                                    ToolTip="保存" Margin="10,0,0,0">
                                <Button.Content>
                                    <Path Fill="{StaticResource InfoPressedSolidColorBrush}" 
                                          Width="18" Height="18" Stretch="Fill" 
                                          Data="{StaticResource PathSave}"/>
                                </Button.Content>
                            </Button>
                            <Button x:Name="PART_ButtonCancel" Style="{StaticResource PathButton}"
                                    ToolTip="取消">
                                <Button.Content>
                                    <Path Fill="{StaticResource DangerPressedSolidColorBrush}" 
                                          Width="14" Height="14" Stretch="Fill" 
                                          Data="{StaticResource PathCancel}"/>
                                </Button.Content>
                            </Button>
                            <Button x:Name="PART_ButtonComplete"  Style="{StaticResource PathButton}"
                                    ToolTip="完成" Margin="0,0,10,0">
                                <Button.Content>
                                    <Path Fill="{StaticResource SuccessPressedSolidColorBrush}"  
                                          Width="20" Height="15" Stretch="Fill" 
                                          Data="{StaticResource PathComplete}"/>
                                </Button.Content>
                            </Button>
                        </WrapPanel>

                    </Canvas>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
</Style>
</ResourceDictionary>

三、ScreenCutExample.xaml 代碼如下

var screenCut = new ScreenCut();
   screenCut.ShowDialog();

到此這篇關(guān)于WPF仿微信實現(xiàn)截圖功能的方法詳解的文章就介紹到這了,更多相關(guān)WPF截圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • C#基于COM方式讀取Excel表格的方法

    C#基于COM方式讀取Excel表格的方法

    這篇文章主要介紹了C#基于COM方式讀取Excel表格的方法,涉及C# COM組件的調(diào)用與Excel表格的使用技巧,需要的朋友可以參考下
    2016-07-07
  • C#關(guān)于Task.Yeild()函數(shù)的討論

    C#關(guān)于Task.Yeild()函數(shù)的討論

    這篇文章主要介紹了C#中關(guān)于Task.Yeild()函數(shù)的相關(guān)資料,文中講解非常細致,幫助大家更好的理解和學習,感興趣的朋友可以了解下
    2020-07-07
  • C#窗體編程(windows forms)禁止窗口最大化的方法

    C#窗體編程(windows forms)禁止窗口最大化的方法

    這篇文章主要介紹了C#窗體編程(windows forms)禁止窗口最大化的方法,以及避免彈出系統(tǒng)菜單和禁止窗口拖拽的方法,需要的朋友可以參考下
    2014-08-08
  • C#實現(xiàn)寫入文本文件內(nèi)容的方法

    C#實現(xiàn)寫入文本文件內(nèi)容的方法

    這篇文章主要介紹了C#實現(xiàn)寫入文本文件內(nèi)容的方法,涉及C#針對文本文件的判斷、創(chuàng)建及寫入等相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-07-07
  • C#序列化與反序列化(Serialize,Deserialize)實例詳解

    C#序列化與反序列化(Serialize,Deserialize)實例詳解

    這篇文章主要介紹了C#序列化與反序列化(Serialize,Deserialize)的方法,實例分析了C#序列化與反序列化的常見技巧,需要的朋友可以參考下
    2015-06-06
  • C#文件操作類分享

    C#文件操作類分享

    這篇文章主要為大家分享了C#文件操作類的相關(guān)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • C#使用帶like的sql語句時防sql注入的方法

    C#使用帶like的sql語句時防sql注入的方法

    這篇文章主要介紹了C#使用帶like的sql語句時防sql注入的方法,采用了一個比較簡單的字符串過濾方法就可以有效提高sql語句的安全性,防止sql注入,需要的朋友可以參考下
    2014-09-09
  • C#中的Linq Intersect與Except方法使用實例

    C#中的Linq Intersect與Except方法使用實例

    這篇文章主要介紹了C#中的Linq Intersect與Except方法使用實例,本文直接給出示例代碼,需要的朋友可以參考下
    2015-06-06
  • C#?如何獲取當前進程或線程的ID

    C#?如何獲取當前進程或線程的ID

    這篇文章主要介紹了C#?如何獲取當前進程或線程的ID,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-04-04
  • C#實現(xiàn)自定義線程池實例代碼

    C#實現(xiàn)自定義線程池實例代碼

    這篇文章介紹了C#實現(xiàn)自定義線程池的實例代碼,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-07-07

最新評論

莎车县| 平阳县| 汕头市| 江陵县| 敖汉旗| 南陵县| 黄山市| 甘南县| 东莞市| 南充市| 盖州市| 北宁市| 天镇县| 长宁区| 丽水市| 钟山县| 渑池县| 卓尼县| 开化县| 辽中县| 英德市| 胶州市| 玉林市| 宜州市| 准格尔旗| 历史| 墨竹工卡县| 商洛市| 英山县| 社旗县| 霍邱县| 贡嘎县| 济南市| 大厂| 永丰县| 虎林市| 冕宁县| 双江| 香格里拉县| 吉隆县| 泸溪县|