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

相关推荐
Java面试题总结几秒前
C#12 中的 Using Alias
开发语言·windows·c#
加号33 分钟前
【C#】 ASCII 码转字符串技术解析
开发语言·c#
2601_961875241 小时前
高考真题word版下载|2025高考全科真题可编辑文档
c#·word·ar·vr·mr·高考·oneflow
阿正的梦工坊3 小时前
【Rust】09-泛型、Trait 与生命周期基础
开发语言·rust·c#
z落落3 小时前
C# 事件(Event)+自定义带参数事件例子
开发语言·分布式·c#
FlYFlOWERANDLEAF3 小时前
DevExpress Office File API使用记录
开发语言·c#·devoffice
richard_yuu4 小时前
C#工业上位机项目实战第九篇:可视化流程引擎完整落地,节点拖拽、连线渲染与自动化调度
c#·自动化
njsgcs5 小时前
c# solidworks 创建装配体工程图+bom
开发语言·c#·solidworks
njsgcs5 小时前
c# solidworks 工程图获得展开视图不在固定面螺纹特征的位置
开发语言·c#·solidworks
深海潜水员8 小时前
【从零开始的C#游戏开发课程】- FarmStory1.0 日志系统和游戏资源的管理
游戏·c#·monogame