4
votes

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?

2
Can you detect the printer name/type after they have chosen it and put up a dialog box at that point to tell them to pick something else?Gabe
We are using the PrintDialog() method on the ReportViewer control. An exception gets thrown inside the PrintDialog() method when the PDF printer is selected. We could catch the exception and throw up a dialog, but it would be much nicer to just remove the option all together.JChristian

2 Answers

3
votes

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;
}
0
votes

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.