我可以打印标准的测试页中的代码隐藏在.NET 3.5? [英] Can I print a standard test page in code-behind in .NET 3.5?
问题描述
有没有办法从C#代码打印在WPF一个标准的测试页面,如果我有一个网络打印机的名称?
Is there a way to print a standard test page in WPF from C# code if I have the name of a network printer?
谢谢!
推荐答案
下面是使用的例子System.Management命名空间访问WMI,并打印测试页到打印机。这依赖于打印机连接到电脑,我可以,如果你想要的,以及通过System.Management连接网络打印机提供的代码。此代码应工作在.NET Framework
The following is an example of using the System.Management namespace to access WMI and print a Test Page to a Printer. This relies on the Printer being connected to the Computer, I can provide code for connecting a Network printer through System.Management if you want that as well. This code should work for any version of the .Net Framework
using System;
using System.Management;
public class PrintTestPageUsingWMI
{
private String _name;
private ManagementObject _printer = null;
public PrintTestPageUsingWMI(String printerName)
{
this._name = printerName;
//Find the Win32_Printer which is a Network Printer of this name
//Declare WMI Variables
ManagementObject MgmtObject;
ManagementObjectCollection MgmtCollection;
ManagementObjectSearcher MgmtSearcher;
//Perform the search for printers and return the listing as a collection
MgmtSearcher = new ManagementObjectSearcher("Select * from Win32_Printer");
MgmtCollection = MgmtSearcher.Get();
foreach (ManagementObject objWMI in MgmtCollection)
{
if (objWMI.Item("sharename").ToString().Equals(this._name))
{
this._printer = objWMI;
}
}
if (this._printer == null)
{
throw new Exception("Selected Printer is not connected to this Computer");
}
}
public void PrintTestPage()
{
this.InvokeWMIMethod("PrintTestPage");
}
/// <summary>
/// Helper Method which Invokes WMI Methods on this Printer
/// </summary>
/// <param name="method">The name of the WMI Method to Invoke</param>
/// <remarks></remarks>
private void InvokeWMIMethod(String method) {
if (this._printer == null)
{
throw new Exception("Can't Print a Test Page on a Printer which is not connected to the Computer");
}
Object[] objTemp = new Object[0] { null };
ManagementObject objWMI;
//Invoke the WMI Method
this._printer.InvokeMethod(method, objTemp);
}
}
另外,您可以看一下System.Printing其命名空间在.NET 3.0和更高
Alternatively you could look at the System.Printing Namespace which is supported in .Net 3.0 and higher
这篇关于我可以打印标准的测试页中的代码隐藏在.NET 3.5?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!