是否有一种简单的方法来枚举.NET中所有可见的网络打印机?目前,我正在显示PrintDialog以允许用户选择打印机.问题是,本地打印机也会显示(与XPS Document Writer等一起).如果我自己可以枚举网络打印机,我可以只显示那些打印机的自定义对话框.
谢谢!!
从中获取默认打印机 LocalPrintServer.DefaultPrintQueue
从(从用户的角度)获取已安装的打印机 PrinterSettings.InstalledPrinters
列举清单:
任何打印机\\
都是网络打印机 - 所以请使用new PrintServer("\\UNCPATH").GetPrintQueue("QueueName")
任何没有开始的打印机\\
都是本地打印机,所以请使用它LocalPrintServer.GetQueue("Name")
您可以通过比较FullName
属性来查看哪个是默认值.
注意:网络打印机可以是默认打印机LocalPrintServer.DefaultPrintQueue
,但不会出现LocalPrintServer.GetPrintQueues()
// get available printers LocalPrintServer printServer = new LocalPrintServer(); PrintQueue defaultPrintQueue = printServer.DefaultPrintQueue; // get all printers installed (from the users perspective)he t var printerNames = PrinterSettings.InstalledPrinters; var availablePrinters = printerNames.Cast().Select(printerName => { var match = Regex.Match(printerName, @"(? \\\\.*?)\\(? .*)"); PrintQueue queue; if (match.Success) { queue = new PrintServer(match.Groups["machine"].Value).GetPrintQueue(match.Groups["queue"].Value); } else { queue = printServer.GetPrintQueue(printerName); } var capabilities = queue.GetPrintCapabilities(); return new AvailablePrinterInfo() { Name = printerName, Default = queue.FullName == defaultPrintQueue.FullName, Duplex = capabilities.DuplexingCapability.Contains(Duplexing.TwoSidedLongEdge), Color = capabilities.OutputColorCapability.Contains(OutputColor.Color) }; }).ToArray(); DefaultPrinter = AvailablePrinters.SingleOrDefault(x => x.Default);
使用新的System.Printing API
using (var printServer = new PrintServer(string.Format(@"\\{0}", PrinterServerName))) { foreach (var queue in printServer.GetPrintQueues()) { if (!queue.IsShared) { continue; } Debug.WriteLine(queue.Name); } }
在这里找到这个代码
private void btnGetPrinters_Click(object sender, EventArgs e) { // Use the ObjectQuery to get the list of configured printers System.Management.ObjectQuery oquery = new System.Management.ObjectQuery("SELECT * FROM Win32_Printer"); System.Management.ManagementObjectSearcher mosearcher = new System.Management.ManagementObjectSearcher(oquery); System.Management.ManagementObjectCollection moc = mosearcher.Get(); foreach (ManagementObject mo in moc) { System.Management.PropertyDataCollection pdc = mo.Properties; foreach (System.Management.PropertyData pd in pdc) { if ((bool)mo["Network"]) { cmbPrinters.Items.Add(mo[pd.Name]); } } } }
更新:
"此API函数可以枚举所有网络资源,包括服务器,工作站,打印机,共享,远程目录等."
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=741&lngWId=10