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

相关推荐
rockey6273 分钟前
AScript之事件处理脚本
c#·.net·script·动态脚本
蛋蛋的学习记录4 小时前
C#窗体应用中使用EasyModbusCore通讯
服务器·c#·tcp
ShyanZh4 小时前
Markitdown 多格式文档智能解析实战指南
开发语言·c#
周杰伦fans7 小时前
C# CAD 二次开发:无需启动 AutoCAD 实现 DWG 转 DXF 的完整技术指南
开发语言·c#
影寂ldy8 小时前
C# 多态与函数重载(静态多态)
开发语言·c#
小满Autumn9 小时前
依赖注入设计模式速查手册
开发语言·c#·wpf·mvvm·依赖注入
z落落9 小时前
C# 静态成员 vs 非静态成员(调用规则+内存特点)+只读和常量 const常量 / readonly / static readonly 三者终极区别
java·开发语言·c#
Xin_ye1008610 小时前
C# 零基础到精通教程 - WPF 专题三:高级控件与自定义控件
开发语言·c#·wpf
xiaoshuaishuai810 小时前
C# AvaloniaUI‌的IValueConverter
开发语言·c#
z落落10 小时前
C# 虚方法(virtual)与抽象方法 +区别+new方法隐藏 & override方法重写
java·开发语言·c#