Hi,
I am trying to set custom paper size on my printer with Winspool.drv. But getting error as
'Attempted to read or write protected memory.'
Please help. The code is as mentioned below. Let me know if you need any other info.
Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTest.Click
Dim hPrinter&
Dim FI1 As MyPrinterClass.FORM_INFO_1
Dim aFI1() As Byte
Dim RetVal As Integer
Dim ptrFI As IntPtr
MyPrinterClass.OpenPrinter("Microsoft Office Document Image Writer", hPrinter, 0&)
With FI1
.Flags = 0
.pName = "Custom Size"
.size.cx = 1000
.size.cy = 2000
End With
ReDim aFI1(Len(FI1))
ptrFI = Marshal.AllocHGlobal(Marshal.SizeOf(FI1))
Call MyPrinterClass.CopyMemory(aFI1(0), ptrFI, Len(FI1))
RetVal = MyPrinterClass.SetForm(hPrinter, "Microsoft Office Document Image Writer", 2, aFI1(0))
MyPrinterClass.ClosePrinter(hPrinter)
End Sub
Public Class MyPrinterClass
<dllimport("winspool.drv",> SetLastError:=True, CharSet:=CharSet.Ansi, _
ExactSpelling:=True, _
CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function OpenPrinter(ByVal pPrinterName As String, _
ByRef phPrinter As Int32, ByVal pDefault As Int32) As Boolean
End Function
<dllimport("winspool.drv",> SetLastError:=True, _
ExactSpelling:=True, _
CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function ClosePrinter(ByVal hPrinter As Int32) As Boolean
End Function
Declare Function SetForm Lib "winspool.drv" Alias "SetFormA" ( _
ByVal hPrinter As Integer, ByVal pFormName As String, _
ByVal Level As Integer, ByRef pForm As Byte) As Integer
Public Structure SIZEL
Dim cx As Long
Dim cy As Long
End Structure
Public Structure FORM_INFO_1
Dim Flags As Long
Dim pName As String
Dim size As SIZEL
End Structure
Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByVal pDst As IntPtr, _
ByVal pSrc As IntPtr, _
ByVal ByteLen As Long)
End Class