问题
I have program that print labels and I have to allow user to save/remember settings for printer. So I have this code:
private void printerToolStripButton_Click(object sender, EventArgs e)
{
PrintDialog dialog = new PrintDialog();
dialog.ShowDialog();
}
User selects printer and clicks properties button, do some changes (paper size, orientation, etc.) and then click 'OK' and then click 'OK' on PrintDialog.
My problem is that those changes are not remembered... When I click button again or restart application they disappear...
Does anyone know how to persist them in application scope? Or if application scope is impossible, then maybe how to save them in the system (so when I go to control panel -> printers -> right click on printer -> preferences they will be there)?
回答1:
Yu can use my own interface-driven serialization. ;)
You can extend interface-driven serialization using my xml serialization properties. By the way, interface-driven serialization is cool when you are using interface inheritance ;)
using System;
using System.IO;
using System.Windows.Forms;
// download at [http://xmlserialization.codeplex.com/]
using System.Xml.Serialization;
namespace test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[XmlRootSerializer("PrinterSettings")]
public interface IPrinterSettings
{
bool PrintToFile { get; set; }
}
private static readonly string PrinterConfigurationFullName = Path.Combine(Application.StartupPath, "PrinterSettings.xml");
private void Form1_Load(object sender, EventArgs e)
{
if (File.Exists(PrinterConfigurationFullName))
{
XmlObjectSerializer.Load<IPrinterSettings>(File.ReadAllText(PrinterConfigurationFullName), printDialog1);
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
File.WriteAllText(PrinterConfigurationFullName, XmlObjectSerializer.Save<IPrinterSettings>(printDialog1));
}
private void button1_Click(object sender, EventArgs e)
{
if (printDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// do required stuff here...
}
}
}
}
来源:https://stackoverflow.com/questions/4734245/how-to-save-print-settings-from-a-windows-forms-program