Why do we need to display the Print dialog box, because we do not know which printer the user is going to use and the specific Print Options. If we do, we do not need to display this dialog box.
In WPF, printdialog (in the system. Windows. Controls namespace) stores the selected attributes: printqueue and printticket, which respectively represent the selected printer and Print Options.
Note:
BelowCodeReference: system. Printing. dll
And add the namespace: using system. printing;
You can use the localprintserver. getdefaprintprintqueue () method to obtain the default printer.
You can also use localprintserver. getprintqueues to obtain the local printer, and then select the desired printer (or use printserver. getprintqueues to obtain the printer in the workgroup ).
The following code automatically prints a piece of text through the Microsoft XPS document writer printer that comes with the system:
// Note that system. Printing. dll must be referenced and added to using system. printing;
// Initialize printdialog
VaRPrintdialog= New Printdialog();
// Obtain all printer objects (printqueue) from the Local Computer)
VaRPrinters= New Localprintserver().Getprintqueues ();
// Select a printer
VaRSelectedprinter=Printers.Firstordefault (P=>P.Name= "Microsoft XPS document writer");
If(Selectedprinter= Null)
{
MessageBox.Show ("Microsoft XPS document writer printer not found");
Return;
}
// Set the printer
Printdialog.Printqueue=Selectedprinter;
// Create the content to be printed
var TBL = New textblock ( New RUN ( " from: mgen! " );
VaRSize= New Size(Printdialog.Printableareawidth, printdialog.Printableareaheight );
TBL.Measure (size );
TBL.Arrange (New Rect(New Point(0,0), Size ));
// Print
Printdialog.Printvisual (TBL,"Test");
After the code is run, select the XPS storage location and print it successfully: