我想更改非默认打印机的纸张设置,下面代码有两处通不过,谁能帮我看看是什么问题,我的系统是Win7 64位。
Public Function SetPaperSize1(ByVal strPrinterName As String) As Boolean
Dim hPrinter As IntPtr
Dim pi2 As IntPtr
Dim DevMode As New DEVMODE
Dim pDefault As PRINTER_DEFAULTS
Dim InfoPrinter2 As New PRINTER_INFO_2
pDefault.DesiredAccess = PRINTER_ALL_ACCESS '这里不为0打不开打印机
If OpenPrinter(strPrinterName, hPrinter, pDefault) Then
Dim byteNeeded As Integer
Dim returnValue = GetPrinter(hPrinter, 2, IntPtr.Zero, 0, byteNeeded)
If returnValue < 0 Then
Throw New ApplicationException(Marshal.GetLastWin32Error)
End If
pi2 = Marshal.AllocHGlobal(byteNeeded)
returnValue = GetPrinter(hPrinter, 2, pi2, byteNeeded, byteNeeded)
If returnValue = False Then
Throw New ApplicationException(Marshal.GetLastWin32Error)
End If
InfoPrinter2 = DirectCast(Marshal.PtrToStructure(pi2, GetType(PRINTER_INFO_2)), PRINTER_INFO_2)
DevMode = DirectCast(Marshal.PtrToStructure(InfoPrinter2.pDevMode, GetType(DEVMODE)), DEVMODE)
With DevMode
.dmPaperSize = 9
End With
Marshal.StructureToPtr(DevMode, InfoPrinter2.pDevMode, True)
Dim pi3 As IntPtr = pi2
Marshal.StructureToPtr(InfoPrinter2, pi2, True) '程序这里通不过
If Not SetPrinter(hPrinter, 2, pi2, 0&) Then
Throw New ApplicationException(Marshal.GetLastWin32Error)
End If
ClosePrinter(hPrinter)
Marshal.FreeHGlobal(pi2)
Return True
Else
Throw New ApplicationException(Marshal.GetLastWin32Error)
End If
End Function