Hello stackoverflow community, I am developing a simple windows form application that has a listener in a specific directory listening for a txt file, if the listener detects a new file, it will automaticly send the txt file to a local default printer, but it also displays a "Save print output as" dialog and I need the printing proccess to be instant, without having to interact with any dialog.
To do this I am using the current namespace "using System.Drawing.Printing; using System.IO;" and I have seen the definition of the Print() method but seems like the code is protected so I can't have access to remove the "save print output as" dialog. Any ideas?
Here is my code...
The fileWatcher:
private void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e)
{
try
{
MyPrintMethod(e.FullPath);
}
catch (IOException)
{
}
}
My print method:
private void MyPrintMethod(string path)
{
string s = File.ReadAllText(path);
printDocument1.PrintController = new StandardPrintController();
printDocument1.PrintPage += delegate (object sender1, PrintPageEventArgs e1)
{
e1.Graphics.DrawString(s, new Font("Times New Roman", 12), new SolidBrush(Color.Black), new RectangleF(0, 0, printDocument1.DefaultPageSettings.PrintableArea.Width, printDocument1.DefaultPageSettings.PrintableArea.Height));
};
try
{
printDocument1.Print();
}
catch (Exception ex)
{
throw new Exception("Exception Occured While Printing", ex);
}
}
That dialog appears when the printer being used is a document writer, like Microsoft XPS Document Writer
or Microsoft Print to PDF
. Since you don't specify a printer by name, the problem is likely that this is the current default printer.
If you know the name of the printer you want to use, then you can specify it like so:
printDocument1.PrinterSettings.PrinterName =
@"\\printSrv.domain.corp.company.com\bldg1-floor2-clr";
If you don't know the name, then probably the best you can do is ask the user which one they want to print to. You can get a list of the installed printers like this:
var installedPrinters = PrinterSettings.InstalledPrinters;
And then when one is chosen, you can specify the name as in the first code sample. Here's some code that you can use to prompt the user for a printer, and set the printer to the one they choose:
Console.WriteLine("Please select one of the following printers:");
for (int i = 0; i < installedPrinters.Count; i++)
{
Console.WriteLine($" - {i + 1}: {installedPrinters[i]}");
}
int printerIndex;
do
{
Console.Write("Enter printer number (1 - {0}): ", installedPrinters.Count);
} while (!int.TryParse(Console.ReadLine(), out printerIndex)
|| printerIndex < 1
|| printerIndex > installedPrinters.Count);
printDocument1.PrinterSettings.PrinterName = installedPrinters[printerIndex - 1];