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、对于窗体自身,使用该方法有个问题,那就是窗体通常有标题栏,不同于普通的控件,因此捕捉的图片偏移一个标题栏的大小,如何解决就留给大家了,呵呵。

  • 相关阅读:
    python+selenium之页面元素截图
    selenium八大定位
    http概述之URL与资源
    数组中只出现一次的数字
    数字在排序数组中出现的次数
    把数组排成最小的数
    数组中出现次数超过一半的数字
    调整数组顺序使得奇数位于偶数的前面
    旋转数组的最小值
    二维数组的查找
  • 原文地址:https://www.cnblogs.com/lotus/p/540677.html
Copyright © 2011-2022 走看看