3

I'm getting a strange exception from the following code:

 var printDialog = new PrintDialog();
        printDialog.ShowDialog();

        var printDocument = new PrintDocument { DefaultPageSettings = { Landscape = true, PrinterSettings = new PrinterSettings { PrinterName = printDialog.PrintQueue.Name } } };

        var updateResult = new UpdateResult<Image>(UpdateType.Print) { Success = true };
        foreach (string location in fileLocation)
        {
            try
            {
                _printImage = Image.FromFile(location);
                printDocument.PrintPage += PrintRequest;
            }
            catch (Exception exception)
            {
               //various error handling code here
            }
        }
        printDocument.Print();

The final line is throwing a Win32Exception with the detail "The handle is invalid", according to the msdn documentation the only exception that should be thrown is printer not found. The exception seems to be to be some sort of driver/non framework exception.

When I select my printer (Lexmark T640, setup to print directly to the printer port) the code prints fine, but selecting either of the other two printers I have access to (another T640, or a dell colour) the code fails. The other two printers are setup to print through our central print server, but I didn't think this should make any difference. Can anyone give me any pointers?

Edit: Just tried it with printDialog.PrintQueue.Fullname and the behaviour is no different. Substituting in a garbage printer name throws an InvalidPrinterException as expected, suggesting it has found the printer, but seems to fail.

ChrisFletcher
  • 1,010
  • 2
  • 14
  • 31

3 Answers3

0

Try setting the target printer as the default printer (if it isn't already) and see if it still happens

Rob Cowell
  • 1,610
  • 3
  • 18
  • 34
  • I have the same issue. Changing the default printer fixed the problem but this is not a usable solution for me since the user needs to be able to print to any printer on their machine and I can't expect them to constantly be changing their defaults before every print. Any idea how to get PrintDocument to behave properly? – Bitfiddler Dec 17 '14 at 19:57
0

I got this exception only when printing multiple documents. My solutions was to add

printDocument.Dispose(); after printDocument.Print();.

Brett
  • 3
  • 5
0

For @Matt's benefit. I didn't manage to figure out what the issue was in the end, could well be something to do with the configuration of our network but that's out of my hands.

Instead I used a different method, I used CommonDialogClass.ShowPhotoPrintingWizard() which is part of Interop.WIA as below.

http://msdn.microsoft.com/en-us/library/windows/desktop/ms630492%28v=vs.85%29.aspx

This hands over the process to the photo printing wizard and I've not had any issues since.

ChrisFletcher
  • 1,010
  • 2
  • 14
  • 31