標籤:
實現如下效果:
實現方式如下:
using System;
using System.Drawing.Printing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace PISS.View.CustomControl
{
public partial class PrinterConfigMessBox : Form
{
#region 定義、構造、初始化
[DllImport("winspool.drv")]
//調用win api將指定名稱的印表機設定為預設印表機
public static extern bool SetDefaultPrinter(String Name);
private static PrintDocument PrintDocument = new PrintDocument();
public string PrinterName { get; set; }
//擷取本機預設印表機名稱
public static String DefaultPrinter()
{
return PrintDocument.PrinterSettings.PrinterName;
}
public PrinterConfigMessBox(string message)
{
InitializeComponent();
this.lblMessage.Text = message;
}
private void PrinterConfigMessBox_Load(object sender, EventArgs e)
{
foreach (var item in PrinterSettings.InstalledPrinters)
{
this.tvList.Nodes.Add(item.ToString());
}
PrinterName = PrintDocument.PrinterSettings.PrinterName;
SetDefaultSelectNode();
}
/// <summary>
/// 設定預設選中項
/// </summary>
private void SetDefaultSelectNode()
{
foreach (TreeNode item in this.tvList.Nodes)
{
if (!item.Text.Equals(PrinterName)) continue;
this.tvList.SelectedNode = item;
break;
}
}
#endregion
#region event
private void btnPrint_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
private void tvList_AfterSelect(object sender, TreeViewEventArgs e)
{
PrinterName = this.tvList.SelectedNode.Text;
PrinterConfigMessBox.SetDefaultPrinter(PrinterName);
SetDefaultSelectNode();
}
#endregion
}
}
C#Winfrom系統印表機調用/設定預設印表機