打印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,还有实现分页打印等

相关推荐
BuHuaX6 小时前
Unity_数据持久化_IXmlSerializable接口
xml·unity·c#·游戏引擎·游戏策划
格林威6 小时前
Baumer工业相机堡盟工业相机如何通过YoloV8深度学习模型实现路口车辆速度的追踪识别(C#代码UI界面版)
人工智能·深度学习·数码相机·yolo·计算机视觉·c#·视觉检测
CodeCraft Studio7 小时前
国产化Word处理控件Spire.Doc教程:Python提取Word文档中的文本、图片、表格等
python·c#·word·国产化·spire.doc·word文档处理·文档开发控件
Kookoos7 小时前
ABP VNext + Quartz.NET vs Hangfire:灵活调度与任务管理
c#·.net·hangfire·quartz.net·abp vnext
LZQqqqqo10 小时前
C# 事件Event
开发语言·c#
时光追逐者10 小时前
C#/.NET/.NET Core优秀项目和框架2025年7月简报
c#·.net·.netcore
与火星的孩子对话11 小时前
Unity Shader编程完全入门指南:从零到实战 C# 实战案例
unity·c#·游戏引擎
R-G-B12 小时前
【08】大恒相机SDK C#发开 —— 多相机采集
c#·大恒相机c#发开·大恒多相机采集
一个会的不多的人13 小时前
C# NX二次开发:超级点控件使用详解
开发语言·c#
LZQqqqqo20 小时前
C# 中生成随机数的常用方法
java·算法·c#