当前位置: 首页 > news >正文

把wpf的窗体保存为png图片

昨晚在stack  overflow刷问题时看到有这个问题,今天早上刚好来尝试学习一下

stack overflow的链接如下:

c# - How to render a WPF UserControl to a bitmap without creating a window - Stack Overflow

测试步骤如下:

1  新建.net framework 3.5的wpf窗体程序

2 默认的窗体的xaml代码如下:

<Window x:Class="WpfDemo.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:WpfDemo"xmlns:s="clr-namespace:System;assembly=mscorlib"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Grid><StackPanel HorizontalAlignment="Left"><TextBox>123455</TextBox><Button x:Name="btnEnter" Click="BtnEnter_Click" Content="确定"></Button></StackPanel></Grid>
</Window>

窗体效果如下:

对应的后台代码如下:

using System;
using System.Collections.Generic;
using System.IO;
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.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;namespace WpfDemo
{/// <summary>/// MainWindow.xaml 的交互逻辑/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}private void BtnEnter_Click(object sender, RoutedEventArgs e){RenderControl(this);MessageBox.Show("保存完成");}void RenderControl(Control renderControl){RenderTargetBitmap bmp = new RenderTargetBitmap((int)renderControl.Width, (int)renderControl.Height, 0, 0, PixelFormats.Pbgra32);bmp.Render(renderControl);var encoder = new PngBitmapEncoder();encoder.Frames.Add(BitmapFrame.Create(bmp));using (Stream stm = File.Create("test.png"))encoder.Save(stm);}}
}

3  运行程序,点击确定按钮,会在bin/Debug目录下生成MainWindow窗体对应的png图片,png图片名称为test.png,如下图:

http://www.lryc.cn/news/224922.html

相关文章:

  • 2023NOIP A层联测28-大眼鸹猫
  • 电机应用-直流有刷电机
  • BIM、建筑机器人、隧道工程施工关键技术
  • 快速了解什么是跳跃表(skip list)
  • 【Node.js入门】1.1Node.js 简介
  • 数据库 高阶语句
  • jenkins Java heap space
  • OpenCV校准棋盘集合
  • 使用git将本地项目推送到远程仓库github
  • Mybatis-Plus使用Wrapper自定义SQL
  • 仿mudou库one thread one loop式并发服务器
  • 二十三种设计模式全面解析-组合模式与装饰器模式的结合:实现动态功能扩展
  • 智慧城市建设解决方案分享【完整】
  • unity - Blend Shape - 变形器 - 实践
  • asp.net core mvc之路由
  • 前端设计模式之【访问者模式】
  • 通过docker-compose部署elk日志系统,并使用springboot整合
  • 【NLP】特征提取: 广泛指南和 3 个操作教程 [Python、CNN、BERT]
  • 数据结构-单链表
  • 红队系列-IOT安全深入浅出
  • 亚数受邀参加“长三角G60科创走廊量子密码应用创新联盟(中心)”启动仪式
  • 直方图学习
  • Java / Android 多线程和 synchroized 锁
  • 基于51单片机的万年历-脉搏计仿真及源程序
  • 【ARFoundation学习笔记】点云与参考点
  • uni-app:js实现数组中的相关处理-数组复制
  • 8 STM32标准库函数 之 实时时钟(RTC)所有函数的介绍及使用
  • ARMday04(开发版简介、LED点灯)
  • 国际腾讯云:云服务器疑似被病毒入侵问题解决方案!!!
  • Perl语言用多线程爬取商品信息并做可视化处理