gpt4 book ai didi

c# - 如何引用资源?

转载 作者:太空宇宙 更新时间:2023-11-03 13:40:08 24 4
gpt4 key购买 nike

我如何将下面的代码引用到 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, "");

最佳答案

如果您要打印的资源是您的应用程序资源的一部分,即直接添加到 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);
}
}

关于c# - 如何引用资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17408581/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com