使用c#设置Windows的默认打印机

我想在按钮单击时为Windows /系统设置设置默认打印机。 我想点击一个按钮,并希望出现一个窗口对话框,要求用户设置默认打印机。 现在我正在使用PrintDialog,但每次单击按钮时它都会更改打印机。 我想将所选打印机设置为默认打印机,即使我关闭应用程序也应该保持不变。

private void PrintSettingsBtn_Click(object sender, EventArgs e) { PrintDialog PrintDialog = new PrintDialog(); PrintDialog.ShowDialog(); PrinterName = PrintDialog.PrinterSettings.PrinterName; } 

尝试使用SetDefaultPrinter Windows API函数

  using System.Runtime.InteropServices; ... [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern Boolean SetDefaultPrinter(String name); ... SetDefaultPrinter(PrinterName); 

看到

http://msdn.microsoft.com/en-us/library/windows/desktop/dd162971(v=vs.85).aspx http://www.pinvoke.net/default.aspx/winspool/SetDefaultPrinter.html? DIFF = Y

在Solution Explorer中右键单击项目,选择Properties。 选择Settings选项卡,添加PrinterName设置。

在代码中使用设置:

 string PrinterName { get { return (string)Properties.Settings.Default["PrinterName"]; } set { Properties.Settings.Default["PrinterName"] = value; Properties.Settings.Default.Save(); } } private void print_Click(object sender, EventArgs e) { PrintDialog pd = new PrintDialog(); if (PrinterName != "") pd.PrinterSettings.PrinterName = PrinterName; if (pd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { // Print PrinterName = pd.PrinterSettings.PrinterName; } }