2

以下のコードを c# で参照して印刷するにはどうすればよいでしょうか。印刷時にウィンドウを表示するのではなく、ボタンから直接印刷したいので、リソース ディクショナリを使用しました。

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<DockPanel Name="dockpanel" Width="auto"    LastChildFill="True" x:Key="Maindock">
        <Grid DockPanel.Dock="top" Width="340" >
</DockPanel>

印刷コードは次のとおりです。

//System.Printing
//get selected printer capabilities
System.Printing.PrintCapabilities capabilities =                 
                printDlg.PrintQueue.GetPrintCapabilities(printDlg.PrintTicket);

//get the size of the printer page
Size sz = new Size(capabilities.PageImageableArea.ExtentWidth,
                   capabilities.PageImageableArea.ExtentHeight);

// update the layout of the visual to the printer page size.
Print.Measure(sz);
Print.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth,
              capabilities.PageImageableArea.OriginHeight), sz));

//now print the visual to printer to fit on the one page.
//printDlg.PageRangeSelection(printQty);
//now print the visual to printer to fit on the one page.
String printerName = "Brother DCP-7045N Printer";

System.Printing.PrintQueue queue = new System.Printing.LocalPrintServer()
                                               .GetPrintQueueprinterName);
printDlg.PrintQueue = queue;

printDlg.PrintVisual(Print, "");
4

1 に答える 1

1

印刷するリソースがアプリケーション リソースの一部である場合、つまり、以下に示すように App.xaml ファイルに直接追加されている場合、またはマージされた辞書を介して追加されている場合は、ビジュアル要素を新しく作成してコンテンツを設定するだけで済みます。 . ここでは、this.FindResource() を使用して、コンテンツとして設定するリソースのインスタンスを取得しています。

注:印刷するために、更新されたページを表示する必要はありません。

アプリケーション リソース

<Application x:Class="PrintTest.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="MainWindow.xaml">
    <Application.Resources>
        <Grid x:Key="PrintTestResource">
            <TextBlock FontSize="50" HorizontalAlignment="Center" VerticalAlignment="Center">Hello World</TextBlock>
        </Grid>
    </Application.Resources>
</Application>

コードを印刷

public void Print()
{
    var printDialog = new PrintDialog();
    if (printDialog.ShowDialog().Value)
    {
        var printCapabilities = printDialog.PrintQueue.GetPrintCapabilities(printDialog.PrintTicket);
        var printSize = new Size(printCapabilities.PageImageableArea.ExtentWidth, printCapabilities.PageImageableArea.ExtentHeight);

        var printPage = new Page();
        printPage.Content = this.FindResource("PrintTestResource");
        printPage.Measure(printSize);
        printPage.Arrange(new Rect(new Point(printCapabilities.PageImageableArea.OriginWidth, printCapabilities.PageImageableArea.OriginHeight), printSize));

        printDialog.PrintVisual(printPage, String.Empty);
    }
}
于 2013-07-02T06:45:56.423 に答える