How to save print settings from a Windows Forms Program?

送分小仙女□ 提交于 2019-12-11 06:56:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!