I need to change DEVMODE
of printer for current printing task to pass standard and device-specific settings. I do the following:
PrintDocument d = new PrintDocument();
d.PrinterSettings.PrinterName = "Microsoft XPS Document Writer"; // example printer name
byte[] devmode_data; // contains a valid value that is obtained from registry
IntPtr devmode = IntPtr.Zero;
GCHandle handle = GCHandle.Alloc(devmode_data, GCHandleType.Pinned);
try
{
devmode = handle.AddrOfPinnedObject();
if (devmode != IntPtr.Zero) d.PrinterSettings.SetHdevmode(devmode);
}
finally
{
if (handle.IsAllocated) handle.Free();
}
It fails when I attempt to execute PrinterSettings.SetHdevmode
with a NullReferenceException
and without any meaningful error info. d.PrinterSettings
is not null, the exception is thrown inside of PrinterSettings.SetHdevmode
method.
So my question is: what is wrong? Is the byte[]
to IntPtr
cast wrong? Maybe SetHdevmode
expects something other than a byte[]
array?
I get the byte[] devmode_data
array from the registry. It is a valid value and it is same value that is used in current printer settings.