PrintDocument.Print() throws a Win32Exception
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开发者_StackOverflow中文版 garbage printer name throws an InvalidPrinterException as expected, suggesting it has found the printer, but seems to fail.
Try setting the target printer as the default printer (if it isn't already) and see if it still happens
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.
I got this exception only when printing multiple documents. My solutions was to add
printDocument.Dispose();
after printDocument.Print();
.
精彩评论