C#/WPF

[C# / WPF] UI 스크린샷 (Capture)

F급 개발자 2023. 7. 24. 21:40
728x90
반응형

해당 포스트는 C# WPF .NET 6 기반, NuGet "CommunityToolkit.Mvvm"으로 작성되었습니다.

 

MainWindow.xaml

<Window x:Class="DataBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DataBinding"
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        mc:Ignorable="d"
        Title="MainWindow" x:Name="Main" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
             <DataGrid                       
                    Margin="5"
                    AutoGenerateColumns="False"
                    CanUserAddRows="False"
                    FontSize="11"
                    IsReadOnly="False"
                    ItemsSource="{Binding DataGrid}">
                <DataGrid.Columns>
                    <DataGridTextColumn
                                    Binding="{Binding DataGrid_NO}"
                                    Header="No" />
                    <DataGridTextColumn
                                    Binding="{Binding DataGrid_Name}"
                                    Header="Name" />
                <DataGridTemplateColumn Header="Icon">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel HorizontalAlignment="Center" Orientation="Horizontal">
                                <materialDesign:PackIcon
                                        Width="20"
                                        Height="20"
                                        HorizontalAlignment="Center"
                                        VerticalAlignment="Center"
                                        Foreground="{Binding DataGrid_Icon_fore}"
                                        Kind="{Binding DataGrid_Icon_kind}" />
                            </StackPanel>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
            </DataGrid>
        <Grid Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>

            <Button Grid.Column="0" Content="버튼" Command="{Binding Btn_ButtonCommand}"/>
            <Button Grid.Column="1" Content="캡처" Command="{Binding Btn_CaptureCommand}"/>
        </Grid>
    
    </Grid>
</Window>

 

MainWindow.cs

using System.Windows;

namespace DataBinding
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Main_Model.mainWindow = this;
            DataContext = Main_Model.main_ViewModel;
        }
    }
}

 

Main_Model.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataBinding
{
    public class Main_Model
    {
        public static Main_ViewModel main_ViewModel = new Main_ViewModel();
        public static MainWindow mainWindow;
    }
}

 

 

Main_ViewModel.cs

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Win32;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace DataBinding
{
    public partial class Main_ViewModel : ObservableObject
    {
        public Main_ViewModel()
        {
            Main_Model.main_ViewModel = this;
            dataGrid = CollectionViewSource.GetDefaultView(datagrid_);
        }

        [ObservableProperty]
        private ICollectionView dataGrid;

        public ObservableCollection<DataGrid_Class> datagrid_ { get; set; } = new ObservableCollection<DataGrid_Class>();

        [RelayCommand]
        private void Btn_Button()
        {
            datagrid_.Add(new DataGrid_Class()
            {
                DataGrid_NO = "1",
                DataGrid_Name = "개발자",
                DataGrid_Icon_kind = "AccountHeart",
                DataGrid_Icon_fore = Brushes.Green
            });
        }

        [RelayCommand]
        private void Btn_Capture()
        {
            capture_Click();
        }
        

        #region 스크린 샷 
        public void capture_Click()
        {

            string fileName = DateTime.Now.ToString("yyyy-MM-dd_hh_mm_ss");
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "";
            saveFileDialog.OverwritePrompt = true;
            saveFileDialog.FileName = DateTime.Now.ToString("yyyy-MM-dd_hh_mm_ss");
            saveFileDialog.Filter = "bmp file(*.bmp)|*.bmp|All file(*.*)|*.all";

            if (saveFileDialog.ShowDialog() == true)
            {
                fileName = saveFileDialog.FileName;
                CaputreControl(Main_Model.mainWindow.Main, fileName);
            }
            else
            {
                return;
            }
        }
        #endregion

        #region 스크린샷 참조
        private void CaputreControl(FrameworkElement element, string filePath)
        {
            Rect rectangle = new Rect(0, 0, element.ActualWidth, element.ActualHeight);

            DrawingVisual visual = new DrawingVisual();

            using (DrawingContext context = visual.RenderOpen())
            {
                VisualBrush brush = new VisualBrush(element);

                context.DrawRectangle(brush, null, new Rect(rectangle.Size));
            }

            int width = (int)element.ActualWidth;
            int height = (int)element.ActualHeight;

            RenderTargetBitmap bitmap = new RenderTargetBitmap
            (
                width,
                height,
                96,
                96,
                PixelFormats.Pbgra32
            );

            bitmap.Render(visual);

            PngBitmapEncoder encoder = new PngBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(bitmap));

            using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                encoder.Save(stream);
            }
        }
        #endregion
    }
}

 

- 실행결과

728x90
반응형

'C# > WPF' 카테고리의 다른 글

[C# WPF] 레이아웃 #2  (0) 2023.07.25
[C# WPF] 레이아웃 #1  (0) 2023.07.24
[C# WPF] Material Design #3  (0) 2023.07.24
[C# WPF] Material Design #2  (0) 2023.07.23
[C# WPF] Material Design #1  (0) 2023.07.23