To achieve the following effects:
The implementation is as follows:
using System;
using System.Drawing.Printing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace PISS.View.CustomControl
{
public partial class PrinterConfigMessBox: Form
{
#region definition, construction, initialization
[DllImport ("winspool.drv")]
// Call win api to set the printer with the specified name as the default printer
public static extern bool SetDefaultPrinter (String Name);
private static PrintDocument PrintDocument = new PrintDocument ();
public string PrinterName {get; set;}
// Get the default printer name of this machine
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>
/// set the default selection
/// </ 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 system printer call / set default printer