I am trying to change the DevMode structure to change the paper source to be used by the PrintDocument.
I know that there is a PaperSource provided by the PrintDocument.PrinterSettings but the requirement of my program is to use our API to change the DevMode and set the new DevMode to the PrintDocument.
When I tried it, the program will successfuly print a document with whatever paper source I provide on the PrintDocument, but only on the first pass. If I execute the same code again, the program will suddenly close without prompting any error when it reaches the PrintDocument.Print().
I'm using VB 2003.
Here's the code snippet:
Expand|Select|Wrap|Line Numbers
- Private WithEvents pd As New PrintDocument
- ...
- // The following lines are part of the click event handler:
- Dim dm, hInstance as IntPtr
- Dim dmSize as Int32
- ...
- dm = Nothing
- GetDevMode(hInstance, dm, dmSize) //Gets the size of the DevMode
- dm = Marshal.AllocCoTaskMem(dmSize) //Allocate memory
- GetDevMode(hInstance, dm, dmSize) //Set the DevMode
- pd.PrinterSettings.SetHDevMode(dm)
- pd.Print() //Program fails here on the next execution
- ...
- Marshal.FreeCoTaskMem(dm)
- ...
GetDevMode will consistently set the dmSize, while it also sets the dm to point to a memory location, thus I can say that there is no problem on our GetDevMode API (and, we have a version in C++ of the same program, using the same API and it works perfectly fine.)
Did I miss something on the settings of the PrintDocument or misuse the Interop/Marshal functions?
I hope somebody can help me with this.. or even at least give me ideas on how to solve it.
Thank you..