标签:
项目中,需要选择打印机,切换打印机。demo如下(wpf应用程序):
Xaml:
<Window x:Class="PrintersApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <StackPanel> <ComboBox x:Name="printerComboBox"/> <Button Content="设置成打印机" Click="setDefaultPrintBtn"/> </StackPanel> </Grid> </Window>
打印机LocalPrinter类:
public class LocalPrinter { private static PrintDocument fPrintDocument = new PrintDocument(); //获取本机默认打印机名称 public static String DefaultPrinter() { return fPrintDocument.PrinterSettings.PrinterName; } public static List<String> GetLocalPrinters() { List<String> fPrinters = new List<String>(); 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将指定名称的打印机设置为默认打印机 }
逻辑代码:
/// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); InitprinterComboBox(); //初始化打印机下拉列表选项 } private void InitprinterComboBox() { List<String> list = 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,选择要设置为默认的打印机,点击“设置成默认打印机”按钮,设置成功:
标签:
原文地址:http://www.cnblogs.com/527289276qq/p/4671488.html