Introduction
It's very often to store user defined printer settings to disk, to get it later
back from the disk. In the framework there is a class called
PrinterSettings
to
manipulate the settings which are chosen by the printer dialog. In the framework
1.1 there is no way to serialize the
PrinterSettings
and store it to the disk.
I think it's a bug in the framework?
Background
In some newsgroups there is always the same question, how can I store
PrinterSettings
in .NET. Now I tried different ways to do that, but I hope the best
one is presented here. Its a mix of managed and unmanaged code. If you try to
serialize the
PrinterSettings
object in the framework there appears always a
serialization exception.
Using the code
The main class is clsPrinterSettings
. In that class we will do
the handling to serialize the class and the object.
There are three methods and two structures. The first method is
public
void setPrinterSettings(PrinterSettings settings)
, this method
stores the
settings
object in the class. After you choose that
method, you can serialize the
clsPrinterSettings
with normal
.NET mechanisms. If you want to get back the settings next time, first you have
to de-serialize the
clsPrinterSettings
and call the second method
public PrinterSettings getPrinterSettings()
, you get
back the restored
PrinterSettings
object. The third method is
private
, because it's used to initialize a new
PrinterSettings
object in the
clsPrinterSettings
. That object is declared in the
class as
NonSerialized()
. If you don't do that, you get a
serialization exception. The two structures are to store the
Hdevmodes
and the
Hdevnames
in the structures.
Using the clsPrinterSettings
- Declaration of the classes is as shown below. The
clsPrinterSettings
is
responsible to serialize the settings of the PrtSettings
object.
private clsPrinterSettings printSet = new clsPrinterSettings();
private BinaryFormatter serializer = new BinaryFormatter();
private PrintDialog printer = new PrintDialog();
private PrinterSettings PrtSettings = new PrinterSettings();
- Check if a serialized file exists. If exists, de-serialize it and assign it to
the
PrtSettings
object.
if (File.Exists(sFilePrinterSet)){
Stream Stream2 = File.Open(sFilePrinterSet, FileMode.Open);
printSet = (clsPrinterSettings) serializer.Deserialize(Stream2);
Stream2.Close();
PrtSettings = printSet.getPrinterSettings();
}
else{
PrtSettings.PrinterName = txtSelPrinter.Text;
}
- Assign the
PrtSettings
object to the Printer.PrinterSettings
property and show the dialog.
printer.PrinterSettings = PrtSettings;
printer.ShowDialog();
- Serialize the
printSet
object after you assigned the new settings
printSet.setPrinterSettings(PrtSettings);
Stream Stream1 = File.Open(sFilePrinterSet, FileMode.Create);
serializer.Serialize(Stream1,printSet);
Stream1.Close();
History
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.