Click here to Skip to main content
11,923,948 members (65,396 online)
Rate this:
Please Sign up or sign in to vote.
See more: VB VB.NET

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"
   = 1000
   = 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))
    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
Posted 4-Nov-11 3:08am
Edited 4-Nov-11 3:10am
Prerak Patel141.4K

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web01 | 2.8.151125.3 | Last Updated 4 Nov 2011
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100