试图用C#打印表单

时间:2013-10-10 21:08:51

标签: c# .net bitmap

自从上一个问题以来,我已经在C#中打印表单了,我现在已经有了这个代码:

    public void printToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Rectangle bounds = this.Bounds;
        Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height);

        Graphics g = Graphics.FromImage(bitmap);            
        g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);             


        PrintDocument doc = new PrintDocument();
        doc.PrintPage += this.Doc_PrintPage;

        PrintDialog dlgSettings = new PrintDialog();
        dlgSettings.Document = doc;

        if (dlgSettings.ShowDialog() == DialogResult.OK)
        {
            doc.Print();
        }
    }

    private void Doc_PrintPage(object sender, PrintPageEventArgs e)
    {

        float x = e.MarginBounds.Left;
        float y = e.MarginBounds.Top;

        e.Graphics.DrawImage(bitmap);
    }

其中printToolStripMenuItem_Click是打印按钮。我知道我很亲密,因为在编辑代码以满足我的需求之前,我看到了打印对话。现在,我收到的错误是“e.Graphics.DrawImage(bitmap);”中的“bitmap”。在上下文中不存在。

我可以更改什么才能打印图像?在尝试创建打印文档之前,我正在尝试打印屏幕图像,因为这看起来更容易,只是因为它有效。我有时候很懒:P

注意:这是我的form2.cs文件中的所有代码,我需要打印的表单。

谢谢:)

2 个答案:

答案 0 :(得分:1)

您在printToolStripMenuItem_Click中声明了位图,但在Doc_PrintPage中使用了该位图。你需要以某种方式传递它。最简单的方法是使它成为一个实例变量(即在类而不是方法中声明它,然后在printToolStripMenuItem_Click中分配它。)

public class SomeForm
{
  private Bitmap bitmap;
  public void printToolStripMenuItem_Click(object sender, EventArgs e)
  {
    //...
    bitmap = new Bitmap(bounds.Width, bounds.Height);
    //...
  }
}

您还缺少e.Graphics.DrawImage来电中的参数。您需要指定绘制图像的位置。例如,如果你想在左上角做它:

e.Graphics.DrawImage(bitmap, new Point(0,0));

答案 1 :(得分:1)

您应该使用匿名方法在函数内创建事件处理程序 通过这种方式,它仍然可以通过闭包的魔力来读取您的局部变量。

doc.PrintPage += (s, e) => {
    float x = e.MarginBounds.Left;
    float y = e.MarginBounds.Top;

    e.Graphics.DrawImage(bitmap);
};