UsingSystem;UsingSystem.Collections.Generic;UsingSystem.Linq;UsingSystem.Text;UsingSystem.Windows;UsingSystem.Windows.Controls;UsingSystem.Windows.Data;UsingSystem.Windows.Documents;UsingSystem.Windows.Input;UsingSystem.Windows.Media;UsingSystem.Windows.Media.Imaging;UsingSystem.Windows.Navigation;UsingSystem.Windows.Shapes;Namespaceprinters{///<summary>///Interaction Logic for Window1.xaml///</summary>PublicPartialClassWindow1:window {PublicWindow1 () {InitializeComponent (); Initprintercombobox ();//Initialize printer drop-down list options}PrivatevoidInitprintercombobox () {list<string> List = Localprinter.getlocalprinters ();//Get a list of printers in the systemforeach (String sInchList) {PRINTERCOMBOBOX.ITEMS.ADD (s);//Add the printer name to the drop-down box} }Privatevoid printButton_Click (Objectsender, RoutedEventArgs e) {if (Printercombobox.selecteditem! =null) // Determine if there is a check value { if (Externs.setdefaultprinter (printerComboBox.SelectedItem.ToString ())) // Set default printer {MessageBox.Show (printerComboBox.SelectedItem.ToString () + " Set as default printer succeeded! "); } else {MessageBox.Show (printerComboBox.SelectedItem.ToString () + " Set as default printer failed! "); } } } }}
LocalPrinter.cs
Press CTRL + C to copy the codeUsing system;using system.collections.generic;using system.linq;using system.text;using System.Drawing.Printing; Using System.runtime.interopservices;namespace printers{class LocalPrinter {private static PrintDocument FP Rintdocument = new PrintDocument (); Get the native default printer name public static String Defaultprinter () {return fPrintDocument.PrinterSettings.Print Ername; } public static list<string> Getlocalprinters () {list<string> fprinters = new LIST&L T String> (); Fprinters.add (Defaultprinter ()); The default printer always appears in the first item of the list, foreach (String fprintername in printersettings.installedprinters) { if (!fprinters.contains (Fprintername)) {Fprinters.add (fprintername); }} return fprinters; } }}Press CTRL + C to copy the code
Externs.cs
UsingSystem;UsingSystem.Collections.Generic;Using System.Linq; using System.text; Using System.runtime.interopservices; Namespace printers{class externs {[DllImport ( Winspool.drv ")] Public static extern BOOL SetDefaultPrinter (String Name); // Call the win API to set the printer with the specified name as the default printer /span>
C # Gets a list of local printers and sets the specified printer as the default printer