没有ShowDialog的打印会显示空白页面

Lee*_*son 8 c# printing wpf

我遇到了一个从WPF项目打印的奇怪问题.我正在打印应用程序的屏幕截图以进行报告,所有这些都可以正常工作.当前用户按下打印,出现打印对话框,并打印出捕获图像.

但是,我希望能够直接打印到默认打印机而不显示对话框.这应该通过评论ShowDialog()声明并允许其余部分恰好发生来轻松完成.打印机仍然打印,但页面始终为空白.谁能解释这种行为?

private void PrintCurrentScreen()
{
    PrintDialog PD = new PrintDialog();
    PD.PrintTicket.OutputColor = OutputColor.Grayscale;
    PD.PrintTicket.OutputQuality = OutputQuality.Draft;

    PrintTicket PT = new PrintTicket();
    PT.PageOrientation = PageOrientation.Landscape;
    PT.CopyCount = 1;
    PT.PageBorderless = System.Printing.PageBorderless.Borderless;

    //---Blank pages print when commented out---//
    //if (PD.ShowDialog() == true)
    //{
    PD.PrintTicket = PT;

    DrawingVisual DV = new DrawingVisual();
    DV.Offset = new Vector(20, 20);
    DrawingContext DC = DV.RenderOpen();
    DC.DrawImage(previewimage.Source, new Rect(new Size(PD.PrintableAreaWidth - 40, PD.PrintableAreaHeight - 40)));
    DC.Close();

    PD.PrintVisual(DV, "TEST");
    //}
}
Run Code Online (Sandbox Code Playgroud)

dig*_*que 2

尝试在打印视觉之前执行 Measure、Arrange 和 UpdateLayout,如下所示:

DV.Measure(new System.Windows.Size(PD.PrintableAreaWidth,
              PD.PrintableAreaHeight));
DV.Arrange(new System.Windows.Rect(new System.Windows.Point(0, 0),
              DV.DesiredSize));

DV.UpdateLayout();
PD.PrintVisual(DV, "TEST");
Run Code Online (Sandbox Code Playgroud)