项目中,需要选择打印机,切换打印机。demo如下(wpf应用程序):
Xaml:
打印机LocalPrinter类:
public class LocalPrinter { private static PrintDocument fPrintDocument = new PrintDocument(); //获取本机默认打印机名称 public static String DefaultPrinter() { return fPrintDocument.PrinterSettings.PrinterName; } public static ListGetLocalPrinters() { List fPrinters = new List (); fPrinters.Add(DefaultPrinter()); //默认打印机始终出现在列表的第一项 foreach (String fPrinterName in PrinterSettings.InstalledPrinters) { if (!fPrinters.Contains(fPrinterName)) { fPrinters.Add(fPrinterName); } } return fPrinters; } }
win api :
public class Externs { [DllImport("winspool.drv")] public static extern bool SetDefaultPrinter(String Name); //调用win api将指定名称的打印机设置为默认打印机 }
逻辑代码:
////// MainWindow.xaml 的交互逻辑 /// public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); InitprinterComboBox(); //初始化打印机下拉列表选项 } private void InitprinterComboBox() { Listlist = LocalPrinter.GetLocalPrinters(); //获得系统中的打印机列表 foreach (String s in list) { printerComboBox.Items.Add(s); //将打印机名称添加到下拉框中 } } private void setDefaultPrintBtn(object sender, RoutedEventArgs e) { if (printerComboBox.SelectedItem != null) //判断是否有选中值 { if (Externs.SetDefaultPrinter(printerComboBox.SelectedItem.ToString())) //设置默认打印机 { MessageBox.Show(printerComboBox.SelectedItem.ToString() + "设置为默认打印机成功!"); } else { MessageBox.Show(printerComboBox.SelectedItem.ToString() + "设置为默认打印机失败!"); } } } }
下拉ComboBox,选择要设置为默认的打印机,点击“设置成默认打印机”按钮,设置成功: