在 Windows Forms 應用程式中,常見需求是列出系統所有已安裝的印表機,並自動選取預設印表機。.NET 提供 System.Drawing.Printing 命名空間中的 PrinterSettings 與 PrintDocument 類別輕鬆實現此功能。
| 類別 | 關鍵成員 | 用途 |
|---|---|---|
PrintDocument | PrinterSettings.PrinterName | 取得系統預設印表機名稱 |
PrinterSettings | InstalledPrinters (靜態屬性) | 取得所有已安裝印表機名稱集合 (StringCollection) |
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
namespace PrinterListDemo
{
public class MainForm : Form
{
private Label lblPrinter;
private ComboBox cboPrinters;
private Container components = null;
public MainForm()
{
InitializeComponent();
LoadPrinters();
}
private void LoadPrinters()
{
// 1. 取得預設印表機
using (PrintDocument pd = new PrintDocument())
{
string defaultPrinter = pd.PrinterSettings.PrinterName;
// 2. 列舉所有印表機並填入 ComboBox
foreach (string printerName in PrinterSettings.InstalledPrinters)
{
cboPrinters.Items.Add(printerName);
// 3. 設定預設值
if (string.Equals(printerName, defaultPrinter, StringComparison.OrdinalIgnoreCase))
{
cboPrinters.SelectedItem = printerName;
}
}
// 若無印表機則顯示提示
if (cboPrinters.Items.Count == 0)
{
cboPrinters.Text = "系統未安裝印表機";
}
}
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.lblPrinter = new Label();
this.cboPrinters = new ComboBox();
this.SuspendLayout();
// lblPrinter
this.lblPrinter.Location = new Point(8, 24);
this.lblPrinter.Name = "lblPrinter";
this.lblPrinter.Size = new Size(80, 16);
this.lblPrinter.TabIndex = 0;
this.lblPrinter.Text = "選擇印表機:";
// cboPrinters
this.cboPrinters.Location = new Point(96, 22);
this.cboPrinters.Name = "cboPrinters";
this.cboPrinters.Size = new Size(200, 21);
this.cboPrinters.TabIndex = 1;
this.cboPrinters.DropDownStyle = ComboBoxStyle.DropDownList;
// Form
this.ClientSize = new Size(310, 70);
this.Controls.AddRange(new Control[] { this.cboPrinters, this.lblPrinter });
this.Name = "MainForm";
this.Text = "系統印表機列表";
this.ResumeLayout(false);
}
#endregion
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new MainForm());
}
}
}
回傳 PrinterSettings.StringCollection,實作 IEnumerable,可直接用 foreach 迭代。
若系統無法列舉印表機(如印表機服務未啟動),會拋出 Win32Exception,建議包裝在 try-catch 中處理。
使用 StringComparison.OrdinalIgnoreCase 確保跨語系環境下正確比對預設印表機名稱。
private void cboPrinters_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboPrinters.SelectedIndex >= 0)
{
using (PrintDocument pd = new PrintDocument())
{
pd.PrinterSettings.PrinterName = cboPrinters.SelectedItem.ToString();
// 後續列印作業將使用此印表機
}
}
}
透過 PrinterSettings.InstalledPrinters 靜態屬性與 PrintDocument 取得預設值,僅需幾行程式碼即可完整實現印表機列舉與預設選取功能,適用於所有 .NET Framework / .NET Core / .NET 5+ 的 Windows Forms 專案。