简体   繁体   English

如何从.Net打印对话框中删除打印机?

[英]How can I remove a printer from the .Net print dialog?

I am working on a Winforms application that allows users to print a few different Reporting Services reports. 我正在开发一个Winforms应用程序,允许用户打印一些不同的Reporting Services报告。 Unfortunately, if the user tries to print to PDF using the Adobe PDF printer, it crashes. 不幸的是,如果用户尝试使用Adobe PDF打印机打印到PDF,它就会崩溃。 We haven't been able to solve this issue, so as a work around we want remove the ability for users to print to the Adobe PDF printer. 我们无法解决这个问题,因此我们想要解决这个问题,删除用户打印到Adobe PDF打印机的能力。

Is there any way to programmatically remove the Adobe PDF printer from the list of printers in the print dialog? 有没有办法以编程方式从打印对话框中的打印机列表中删除Adobe PDF打印机?

Call this with the printer name before calling PrintDialog().... I think this will solve your issue 在调用PrintDialog()之前使用打印机名称调用它。我认为这将解决您的问题

public bool RemovePrinter(string printerName)
{
        ManagementScope scope = new ManagementScope(ManagementPath.DefaultPath);
        scope.Connect();
        SelectQuery query = new SelectQuery("select * from Win32_Printer");
        ManagementObjectSearcher search = new ManagementObjectSearcher(scope, query);
        ManagementObjectCollection printers = search.Get();
        foreach (ManagementObject printer in printers)
        {
            string printerName = printer["Name"].ToString().ToLower();

            if (printerName.Equals(printerName.ToLower()))
            {
                printer.Delete();
                break;
            }
        }                    

        return true;
}

The answer from manish gave me what I needed. manish的答案给了我我需要的东西。 In my case, I had a virtual printer driver that was being created by a library, and it left orphans like Printer (1), Printer (2), etc. I wanted to delete all of those, so I used a variant of the WMI code above. 在我的情况下,我有一个由库创建的虚拟打印机驱动程序,它留下了像打印机(1),打印机(2)等孤儿。我想删除所有这些,所以我使用了一个变体上面的WMI代码。

using System.Management;
//...
var scope = new ManagementScope(ManagementPath.DefaultPath);
scope.Connect();
var query = new SelectQuery($@"select * from Win32_Printer where Name like '{PrinterDeviceName}%'");
foreach (var o in new ManagementObjectSearcher(scope, query).Get()) 
    ((ManagementObject) o).Delete();

You need a reference to System.Management. 您需要对System.Management的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM