[英]How do I set the windows default printer in C#?
如何在 C#.NET 中设置 Windows 默认打印机?
using System;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private void listAllPrinters()
{
foreach (var item in PrinterSettings.InstalledPrinters)
{
this.listBox1.Items.Add(item.ToString());
}
}
private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
string pname = this.listBox1.SelectedItem.ToString();
myPrinters.SetDefaultPrinter(pname);
}
public Form1()
{
InitializeComponent();
listAllPrinters();
}
}
public static class myPrinters
{
[DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetDefaultPrinter(string Name);
}
}
使用 SetDefaultPrinter Windows API。
第 1 步:将以下代码粘贴到 .cs 文件中的任何位置
public static class PrinterClass
{
[DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetDefaultPrinter(string Printer);
}
第 2 步:添加必要的命名空间,即
using System.Runtime.InteropServices;
步骤 3:使用以下功能将所需的打印机设置为默认打印机。
PrinterClass.SetDefaultPrinter("Paste your desired Printer Name here");
第 4 步:要获取连接到 PC 的所有打印机的列表,您可以使用此代码。
private void FillListBox()
{
foreach (var p in PrinterSettings.InstalledPrinters)
{
cmbdefaultPrinter.Properties.Items.Add(p);
}
}
//Here cmbdefaultPrinter is a combobox, you can fill the values into a list.
上述代码所需的命名空间是:
using System.Drawing.Printing;
using System.Runtime.InteropServices;
这是我现在使用的方法。 我包括了 SetDefaultPrinter 方法来提高可靠性。 这是我从其他答案中得出的,并对其进行了修订以反映对我以前的答案版本的反馈。
关于注释:此方法仅适用于正在运行的 C# 应用程序会话的范围内。 此方法不会更改由操作系统管理或存储在注册表中的打印机设置。
using System.Drawing.Printing;
[DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetDefaultPrinter(string Name);
public static PrinterSettings Printer_Settings = new System.Drawing.Printing.PrinterSettings();
/// <summary>
/// Get or Sets the session's Default Printer
/// </summary>
public static string Session_DefaultPrinter
{
get { return Printer_Settings.PrinterName; }
set
{
SetDefaultPrinter(value);
Printer_Settings.DefaultPageSettings.PrinterSettings.PrinterName = value;
Printer_Settings.PrinterName = value;
}
}
典型用法:
string stashPrinterName = Session_DefaultPrinter;
// Switch to my Special Printer
Session_DefaultPrinter = mySpecialPrinter;
// print to my Special Printer
// ...
// Restore the original session's printer
Session_DefaultPrinter = stashPrinterName;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.