由于项目中使用了大量的用户控件,需要提供打印功能,本人尝试了一种简单的控制打印的方法,基于微软的例子并稍作扩充。
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、对于窗体自身,使用该方法有个问题,那就是窗体通常有标题栏,不同于普通的控件,因此捕捉的图片偏移一个标题栏的大小,如何解决就留给大家了,呵呵。

posted on 2006-10-26 14:27  Lotus  阅读(4345)  评论(0编辑  收藏  举报