[點(diǎn)晴永久免費(fèi)OA]C#獲取本地打印機(jī)列表,并將指定打印機(jī)設(shè)置為默認(rèn)打印機(jī)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Printers { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); InitprinterComboBox(); //初始化打印機(jī)下拉列表選項(xiàng) } private void InitprinterComboBox() { List<String> list = LocalPrinter.GetLocalPrinters(); //獲得系統(tǒng)中的打印機(jī)列表 foreach (String s in list) { printerComboBox.Items.Add(s); //將打印機(jī)名稱添加到下拉框中 } } private void printButton_Click(object sender, RoutedEventArgs e) { if (printerComboBox.selectedItem != null) //判斷是否有選中值 { if (Externs.SetDefaultPrinter(printerComboBox.selectedItem.ToString())) //設(shè)置默認(rèn)打印機(jī) { MessageBox.Show(printerComboBox.selectedItem.ToString() + "設(shè)置為默認(rèn)打印機(jī)成功!"); } else { MessageBox.Show(printerComboBox.selectedItem.ToString() + "設(shè)置為默認(rèn)打印機(jī)失敗!"); } } } } } using 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 fPrintDocument = new PrintDocument(); //獲取本機(jī)默認(rèn)打印機(jī)名稱 public static String DefaultPrinter() { return fPrintDocument.PrinterSettings.PrinterName; } public static List<String> GetLocalPrinters() { List<String> fPrinters = new List<String>(); fPrinters.Add(DefaultPrinter()); //默認(rèn)打印機(jī)始終出現(xiàn)在列表的第一項(xiàng) foreach (String fPrinterName in PrinterSettings.InstalledPrinters) { if (!fPrinters.Contains(fPrinterName)) { fPrinters.Add(fPrinterName); } } return fPrinters; } } } using System; using System.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); //調(diào)用win api將指定名稱的打印機(jī)設(shè)置為默認(rèn)打印機(jī) } } 該文章在 2022/7/2 14:15:22 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |