Click here to Skip to main content
15,892,697 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
VB
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))
        'ptraFI = Marshal.AllocHGlobal(Marshal.SizeOf(aFI1(0)))
        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


VB
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
Posted
Updated 4-Nov-11 2:10am
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900