打印Winfrom控件实现简陋版的打印(C#)

本文在前面写的博文基础上进行修改:利用Graphics的CopyFromScreen实现简陋版的打印(C#)_zxy2847225301的博客-CSDN博客

通过截图的方式进行打印在前面的文章后面已经介绍过,有问题。

UI布局如下:

代码如下:

cs 复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace winformDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printDocument1_PrintPage);
            this.button1.Click += new System.EventHandler(this.button1_Click);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            printPreviewDialog1.Document = printDocument1;
            printPreviewDialog1.ShowDialog();
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            PrintToGraphics(e.Graphics, e.MarginBounds);
        }
        public void PrintToGraphics(Graphics graphics, Rectangle bounds)
        {
            Bitmap bitmap = new Bitmap(this.Width, this.Height);
            this.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
            Rectangle target = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            graphics.PageUnit = GraphicsUnit.Display;
            graphics.DrawImage(bitmap, target);
           
        }
    }
}

运行结果如下:

把Form1窗体往任务栏方向挪动,不会出现前面博文中说的那个问题,如下图:

好了,本水文到此结束。后面还有继续深入研究的,如打印单个控件TextBox,Button,还有实现分页打印等

相关推荐
看浪的路人13 分钟前
第10讲:运维 Agent——从「被动救火」到「自动驾驶」
c#·linq
Jazz_z3 小时前
C# 实现 Word 文档内容复制
开发语言·c#·word
huaqianzkh1 天前
WMI 查询入门到实战:从概念、WQL 语法到 C# 采集系统与硬件信息完整示例
开发语言·c#
2395730491 天前
Avalonia 12 代码编辑器性能横评:TKCode.Arc CodeEditor vs AvaloniaEdit 12.0(含深度调优实战)
c#·.net·avalonia·codeeditor·tkcode.arc
张人玉3 天前
C#如何使用FreeSql连接数据库
数据库·c#·freesql
吴可可1234 天前
C#打断多段线实现方法
c#
Kari114 天前
医药和制造行业的外文文档批量翻译,排版怎么保住?
开发语言·c#·制造
Warson_L5 天前
.NET 8 速成笔记 1:用 VS Code 做 C# / .NET 开发
c#·.net
Warson_L5 天前
.NET 8 速成笔记 9:C# 项目常见场景(基础设施篇)
c#·.net
Warson_L5 天前
.NET 8 速成笔记 8:C# 项目常见业务场景与写法(数据与业务篇)
c#·.net