Reputation: 1031
I have an application that will print and email reports to people after the report is rendered and it works great, as long as the printer's driver is installed on the machine running the code. If the machine does not have the driver of the printer installed, it just keeps running the process with no feedback, which took me forever to figure out, because no feedback. Is there a way to check the PrintDocument object to see if a connection can be established and throw an error if there is no connection (no driver)? Here's an example snippet of my code:
PrintDocument pd = new PrintDocument();
using (WindowsImpersonationContext wic = WindowsIdentity.Impersonate(IntPtr.Zero))
{
//code to send printdocument to the printer
//Set Your Printer Name here
printerSettings.PrinterName = printerName;
pd.PrinterSettings = printerSettings;
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
pd.Print(); //If no driver found, the PrintPage Event Handler never fires
}
Upvotes: 1
Views: 859
Reputation: 322
PrinterSettings.IsValid Property
Gets a value indicating whether the PrinterName property designates a valid printer.
if (!pd.PrinterSettings.IsValid)
throw new Exception("this little maneuver would have cost us 51 years");
pd.Print();
true
if the PrinterName property designates a valid printer; otherwise, false.
Upvotes: 0
Reputation: 1031
I actually found an answer that suited my particular situation. Since I won't know the name of the printer I'm looking for and allow a user to put the name of the printer into the client, I can go through the list of installed printers on a machine and make sure that the printer they specified shows up in the list, and if it doesn't, I can throw an exception:
var printerList = PrinterSettings.InstalledPrinters.Cast<string>().ToList();
bool printerFound = printerList.Any(p => p == printerName);
if (printerFound)
{
//Do print stuff
}
else
{
//throw exception or send message
}
Upvotes: 1