Project, you need to select a printer and switch the printer. The demo is as follows (WPF application):
Xaml:
<Windowx:class= "Printersapp.mainwindow"xmlns= "Http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml"Title= "MainWindow"Height= " the"Width= "525"> <Grid> <StackPanel> <ComboBoxx:name= "Printercombobox"/> <ButtonContent= "Set as printer"Click= "Setdefaultprintbtn"/> </StackPanel> </Grid></Window>
View Code
Printer Localprinter class:
Public classLocalPrinter {Private StaticPrintDocument fprintdocument =NewPrintDocument (); //get the native default printer name Public StaticString Defaultprinter () {returnFPrintDocument.PrinterSettings.PrinterName; } Public StaticList<string>getlocalprinters () {List<String> fprinters =NewList<string>(); Fprinters.add (Defaultprinter ()); //The default printer always appears in the first item in the list foreach(String Fprinternameinchprintersettings.installedprinters) {if(!fprinters.contains (Fprintername)) {Fprinters.add (fprintername); } } returnfprinters; } }View Code
Win API:
Public class externs { [DllImport ("winspool.drv")] public Staticexternbool// call the win API to set the specified name of the printer as the default printer }
View Code
Logic code:
/// <summary> ///the interactive logic of MainWindow.xaml/// </summary> Public Partial classMainwindow:window { PublicMainWindow () {InitializeComponent (); Initprintercombobox (); //Initialize printer drop-down list options } Private voidInitprintercombobox () {List<String> list = Localprinter.getlocalprinters ();//get a list of printers in the system foreach(String sinchlist) {PRINTERCOMBOBOX.ITEMS.ADD (s);//Add the printer name to the drop-down box } } Private voidSETDEFAULTPRINTBTN (Objectsender, RoutedEventArgs e) { if(Printercombobox.selecteditem! =NULL)//determine if there are any selected values { if(Externs.setdefaultprinter (PrinterComboBox.SelectedItem.ToString ()))//Set the default printer{MessageBox.Show (printerComboBox.SelectedItem.ToString ()+"Set the default printer to success! "); } Else{MessageBox.Show (printerComboBox.SelectedItem.ToString ()+"Set as default printer failed! "); } } } }View Code
Run:
Drop down ComboBox, select the printer you want to set as the default, click the "Set as Default Printer" button to set the success:
C # Setting the default printer