zoukankan      html  css  js  c++  java
  • WinForm控件的简单打印方法

    由于项目中使用了大量的用户控件,需要提供打印功能,本人尝试了一种简单的控制打印的方法,基于微软的例子并稍作扩充。
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Drawing;
    using System.Data;
    using System.Text;
    using System.Windows.Forms;
    using System.Drawing.Printing;

    namespace PrintTest
    {
        public partial class UserControl1 : UserControl
        {
            public UserControl1()
            {
                InitializeComponent();
            }       

            private void printDocument2_PrintPage(object sender, PrintPageEventArgs e)
            {
                DoPrint(e);           
            } 
         
            protected Bitmap memoryImage;
            protected virtual void DoPrint(PrintPageEventArgs e)
            {
                float leftMargin = e.MarginBounds.Left;
                float topMargin = e.MarginBounds.Top;
                e.Graphics.DrawImage(memoryImage, leftMargin, topMargin, e.MarginBounds.Width, e.MarginBounds.Height);
            }

            private void CaptureScreen(Control ctrl)
            {
                Size s = ctrl.Size;
                memoryImage = new Bitmap(s.Width, s.Height);
                using (Graphics memoryGraphics = Graphics.FromImage(memoryImage))
                {
                    Rectangle rectClient = new Rectangle(0, 0, s.Width, s.Height);
                    Rectangle rectScreen = this.RectangleToScreen(rectClient);
                    memoryGraphics.CopyFromScreen(rectScreen.Left, rectScreen.Top, 0, 0, s);
                }
            }

            private void btnPrint_Click(object sender, EventArgs e)
            {
                PrintPage();
            }

            public void PrintControl(Control ctrl)
            {
                CaptureScreen(ctrl);
                printDocument2.DefaultPageSettings.Landscape = true;
                printDocument2.Print();
            }

            public virtual void PrintPage()
            {
                PrintControl(this);
            }       
        }
    }
    说明:
    1、在自定义控件中添加了一个“打印”按钮,用于打印控件自己。
    PrintPage 和DoPrint方法声明成虚拟方法是为了在子类中可以重定义,毕竟,作为图片打印不是一个好方法。
    2、对于窗体自身,使用该方法有个问题,那就是窗体通常有标题栏,不同于普通的控件,因此捕捉的图片偏移一个标题栏的大小,如何解决就留给大家了,呵呵。

  • 相关阅读:
    freeswitch对媒体的处理的三种方式
    Windows如何在cmd命令行中查看、修改、删除与添加、设置环境变量
    freeswitch电话代接
    freeswitch三方通话配置
    认识拨号计划
    洛谷P4049 [JSOI2007]合金 题解
    2020-9杂题选做
    LOJ#6497. 「雅礼集训 2018 Day1」图 题解
    LOJ#6496. 「雅礼集训 2018 Day1」仙人掌 题解
    LOJ#6495. 「雅礼集训 2018 Day1」树 题解
  • 原文地址:https://www.cnblogs.com/lotus/p/540677.html
Copyright © 2011-2022 走看看