0
votes

When I try to print to a named printer other than my default printer, the system throws an exception "The handle is invalid". However I used the PrinterSettings.IsValid to check before calling print and the print settings are Valid. When I change the default printer to the printer which previously was said to be 'invalid' the exception goes away. This is not a satisfactory solution because my users need to print different things to different printers and they should not have to leave the application to change their default printer. I have also tried creating a 'new' printer settings object with the PrinterName set, but this does not help.

Has anyone seen this before?

The code is somewhat irrelevant because it works so long as you only print to the default printer, however I am using the PrintDocument class to do the printing.

2
are you certain that the code is Irrelevant if so then sounds like you need to put in a helpdesk ticket - MethodMan
Yes I'm sure. Logically if the code works so long as the default printer is set (which is something that happens outside my code) then it's not an error in my code causing the issue. Unless there is a very obscure setting on PrintDocument/PrinterSettings itself, which is essentially the question. - Bitfiddler

2 Answers

0
votes

Okay so an ugly work around was to programmatically change the default printer to the target printer, print the document, then change the default printer back with the following code:

[DllImport("Winspool.drv")]
private static extern bool SetDefaultPrinter(string printerName);

Then in my printing section:

var defaultPrinterName = _printDoc.PrinterSettings.PrinterName;
_printDoc.PrinterSettings.PrinterName = _settings.PrinterName;

if (_printDoc.PrinterSettings.IsValid)
{
    SetDefaultPrinter(_settings.PrinterName);
    _printDoc.Print();
    SetDefaultPrinter(defaultPrinterName); 
} 
0
votes

Are you sure you have the correct printer name? We use the same code to print to a pre-defined pritner and have never had any problems with it. The printer name should be a member of the InstalledPrinters list.

System.Drawing.Printing.PrinterSettings.InstalledPrinters