gpt4 book ai didi

c# - 我可以在 .NET 3.5 的代码隐藏中打印标准测试页吗?

转载 作者:行者123 更新时间:2023-11-30 22:49:56 27 4
gpt4 key购买 nike

如果我有网络打印机的名称,是否可以通过 C# 代码在 WPF 中打印标准测试页?

谢谢!

最佳答案

以下是使用 System.Management 命名空间访问 WMI 并将测试页打印到打印机的示例。这依赖于连接到计算机的打印机,如果您也需要,我可以提供通过 System.Management 连接网络打印机的代码。此代码适用于任何版本的 .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);
}
}

或者,您可以查看 .Net 3.0 及更高版本中支持的 System.Printing 命名空间

关于c# - 我可以在 .NET 3.5 的代码隐藏中打印标准测试页吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/858442/

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