简体   繁体   中英

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. Unfortunately, if the user tries to print to PDF using the Adobe PDF printer, it crashes. 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.

Is there any way to programmatically remove the Adobe PDF printer from the list of printers in the print dialog?

Call this with the printer name before calling PrintDialog().... I think this will solve your issue

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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