L. Guthardt
L. Guthardt

Reputation: 2056

Can't assign new value to property

I am talking about the property PageSettings.PrinterResolution. According to MSDN this property has a setter, same as the property PrinterResolution.X, even though I can't set a new value to it. The property still contains it's earlier value and not the new assigned one.

PrintDocument pd = new PrintDocument();    
//assigning a printer to `pd`, etc...

//premise: pd.DefaultPageSettings.PrinterResolution.X has currently the value 200

Now I try to assign a new int value to X:

pd.DefaultPageSettings.PrinterResolution.X = 300;

But after checking it's value pd.DefaultPageSettings.PrinterResolution.X still contains 200. I just figured out to assign a new PrinterResolution object with set values for X and Y to pd.DefaultPageSettings.PrinterResolution to change the values to my needs.

PrinterResolution changedRes = new PrinterResolution();
changedRes.X = 200;
changedRes.Y = 200;

pd.DefaultPageSettings.PrinterResolution = changedRes;

So why can't I set the values of the property? And especially why is there a documented setter even though it's not "usable".

Upvotes: 1

Views: 142

Answers (1)

René Vogt
René Vogt

Reputation: 43916

If you look at the reference source of PageSettings you see that the PrinterResolution is always re-requested from the API (as long as you don't set the PrinterResolution property manually):

public PrinterResolution PrinterResolution {
    [ResourceExposure(ResourceScope.None)]
    [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
    get {
        if (printerResolution == null) {
            IntSecurity.AllPrintingAndUnmanagedCode.Assert();

            IntPtr modeHandle = printerSettings.GetHdevmode();
            IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(this, modeHandle));
            SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE) UnsafeNativeMethods.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));

            PrinterResolution result = PrinterResolutionFromMode(mode);

            SafeNativeMethods.GlobalUnlock(new HandleRef(this, modeHandle));
            SafeNativeMethods.GlobalFree(new HandleRef(this, modeHandle));

            return result;
        }
        else
            return printerResolution;
    }
    set {
        printerResolution = value;
    }
}

So as long as you don't set PageSettings.PrinterResolution manually, a new PrinterResolution instance is loaded from the API everytime you access the PageSettings.PrinterResolution getter. And this new instance contains the original X value again. The instance for which you set X before is discarded.

As to the why it is like that I don't know enough about.

Upvotes: 5

Related Questions