Answers:
试试这个:
foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
MessageBox.Show(printer);
}
如果您不仅需要打印机名称,还需要更多信息,则可以使用System.Management
API查询它们:
var printerQuery = new ManagementObjectSearcher("SELECT * from Win32_Printer");
foreach (var printer in printerQuery.Get())
{
var name = printer.GetPropertyValue("Name");
var status = printer.GetPropertyValue("Status");
var isDefault = printer.GetPropertyValue("Default");
var isNetworkPrinter = printer.GetPropertyValue("Network");
Console.WriteLine("{0} (Status: {1}, Default: {2}, Network: {3}",
name, status, isDefault, isNetworkPrinter);
}
查看静态System.Drawing.Printing.PrinterSettings.InstalledPrinters属性。
它是系统上所有已安装打印机名称的列表。
在ASP.NET中获取网络和本地打印机列表
此方法使用Windows Management Instrumentation或WMI界面。这是一种用于获取有关Windows操作系统上运行的各种系统(硬件)信息的技术。
private void GetAllPrinterList()
{
ManagementScope objScope = new ManagementScope(ManagementPath.DefaultPath); //For the local Access
objScope.Connect();
SelectQuery selectQuery = new SelectQuery();
selectQuery.QueryString = "Select * from win32_Printer";
ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);
ManagementObjectCollection MOC = MOS.Get();
foreach (ManagementObject mo in MOC)
{
lstPrinterList.Items.Add(mo["Name"].ToString());
}
}
列出了网络和本地打印机的应用程序演示
您也可以使用LocalPrintServer类。请参阅:System.Printing.LocalPrintServer
public List<string> InstalledPrinters
{
get
{
return (from PrintQueue printer in new LocalPrintServer().GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local,
EnumeratedPrintQueueTypes.Connections }).ToList()
select printer.Name).ToList();
}
}
如docs中所述:不支持在Windows服务或ASP.NET应用程序或服务中使用System.Printing命名空间中的类。
如果使用的是MVC C#,则这是处理打印机和串行端口下拉菜单的方法。
using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;
using System.Drawing.Printing;
public class Miclass
{
private void AllViews()
{
List<PortClass> ports = new List<PortClass>();
List<Printersclass> Printersfor = new List<Printersclass>();
string[] portnames = SerialPort.GetPortNames();
/*PORTS*/
for (int i = 0; i < portnames.Count(); i++)
{
ports.Add(new PortClass() { Name = portnames[i].Trim(), Desc = portnames[i].Trim() });
}
/*PRINTER*/
for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
{
Printersfor.Add(new Printersclass() { Name = PrinterSettings.InstalledPrinters[i].Trim(), Desc = PrinterSettings.InstalledPrinters[i].Trim() });
}
}
}
public class PortClass
{
public string Name { get; set; }
public string Desc { get; set; }
public override string ToString()
{
return string.Format("{0} ({1})", Name, Desc);
}
}
public class Printersclass
{
public string Name { get; set; }
public string Desc { get; set; }
public override string ToString()
{
return string.Format("{0} ({1})", Name, Desc);
}
}