如何在 WinFormc# 中打印面板?

Pol*_*ing 3 c# printing panel winforms

我有一个带有标签和数据网格视图的面板。我正在尝试使用此代码打印面板及其内容

    PrintDialog myPrintDialog = new PrintDialog();
        System.Drawing.Bitmap memoryImage = new System.Drawing.Bitmap(panel2.Width, panel2.Height);
        panel2.DrawToBitmap(memoryImage, panel2.ClientRectangle);
        myPrintDialog.ShowDialog();

            System.Drawing.Printing.PrinterSettings values;
            values = myPrintDialog.PrinterSettings;
            myPrintDialog.Document = printDocument1;
            printDocument1.PrintController = new StandardPrintController();
            printDocument1.Print();

        printDocument1.Dispose();
Run Code Online (Sandbox Code Playgroud)

但它什么也不打印。我删除了 datagridview 但仍然没有打印任何内容。然后我更改面板背面颜色,但它再次打印白页。请指导我如何做到这一点?

She*_*ell 5

将此代码添加到PrintPage事件并Print()PrintDocument类对象调用该方法

private void doc_PrintPage(object sender, PrintPageEventArgs e)
{
    float x = e.MarginBounds.Left;
    float y = e.MarginBounds.Top;
    Bitmap bmp = new Bitmap(panel2.Width, panel2.Height);
    panel2.DrawToBitmap(bmp, new Rectangle(0, 0, panel2.Width, panel2.Height));
    e.Graphics.DrawImage((Image)bmp, x, y);
}
Run Code Online (Sandbox Code Playgroud)

像这样调用方法

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

PrintDialog dlg = new PrintDialog();
dlg.Document = doc;
if (dlg.ShowDialog() == DialogResult.OK)
{
    doc.Print();
}
Run Code Online (Sandbox Code Playgroud)