在 vb 中 怎样通过代码设置打印机的横向打印或竖打?

解决方案 »

  1.   

    printer.orientation属性可以设置。但之前需要检查是否对打印机有使用权限(对于NT),否则会出错
      

  2.   

    '改变打印机纸张方向的模块
    'Constants used in the DevMode structure
    Private Const CCHDEVICENAME = 32
    Private Const CCHFORMNAME = 32'Constants for NT security
    Private Const STANDARD_RIGHTS_REQUIRED = &HF0000
    Private Const PRINTER_ACCESS_ADMINISTER = &H4
    Private Const PRINTER_ACCESS_USE = &H8
    Private Const PRINTER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED Or PRINTER_ACCESS_ADMINISTER Or PRINTER_ACCESS_USE)'Constants used to make changes to the values contained in the DevMode
    Private Const DM_MODIFY = 8
    Private Const DM_IN_BUFFER = DM_MODIFY
    Private Const DM_COPY = 2
    Private Const DM_OUT_BUFFER = DM_COPY
    Private Const DM_DUPLEX = &H1000&
    Private Const DMDUP_SIMPLEX = 1
    Private Const DMDUP_VERTICAL = 2
    Private Const DMDUP_HORIZONTAL = 3
    Private Const DM_ORIENTATION = &H1&
    Private PageDirection As Integer
    '------USER DEFINED TYPES'The DevMode structure contains printing parameters.
    'Note that this only represents the PUBLIC portion of the DevMode.
    '  The full DevMode also contains a variable length PRIVATE section
    '  which varies in length and content between printer drivers.
    'NEVER use this User Defined Type directly with any API call.
    '  Always combine it into a FULL DevMode structure and then send the
    '  full DevMode to the API call.
    Private Type DEVMODE
        dmDeviceName As String * CCHDEVICENAME
        dmSpecVersion As Integer
        dmDriverVersion As Integer
        dmSize As Integer
        dmDriverExtra As Integer
        dmFields As Long
        dmOrientation As Integer
        dmPaperSize As Integer
        dmPaperLength As Integer
        dmPaperWidth As Integer
        dmScale As Integer
        dmCopies As Integer
        dmDefaultSource As Integer
        dmPrintQuality As Integer
        dmColor As Integer
        dmDuplex As Integer
        dmYResolution As Integer
        dmTTOption As Integer
        dmCollate As Integer
        dmFormName As String * CCHFORMNAME
        dmLogPixels As Integer
        dmBitsPerPel As Long
        dmPelsWidth As Long
        dmPelsHeight As Long
        dmDisplayFlags As Long
        dmDisplayFrequency As Long
        dmICMMethod As Long        ' // Windows 95 only
        dmICMIntent As Long        ' // Windows 95 only
        dmMediaType As Long        ' // Windows 95 only
        dmDitherType As Long       ' // Windows 95 only
        dmReserved1 As Long        ' // Windows 95 only
        dmReserved2 As Long        ' // Windows 95 only
    End TypePrivate Type PRINTER_DEFAULTS
    'Note:
    '  The definition of Printer_Defaults in the VB5 API viewer is incorrect.
    '  Below, pDevMode has been corrected to LONG.
        pDatatype As String
        pDevMode As Long
        DesiredAccess As Long
    End Type
    '------DECLARATIONSPrivate Declare Function OpenPrinter Lib "winspool.drv" Alias "OpenPrinterA" (ByVal pPrinterName As String, phPrinter As Long, pDefault As PRINTER_DEFAULTS) As Long
    Private Declare Function SetPrinter Lib "winspool.drv" Alias "SetPrinterA" (ByVal hPrinter As Long, ByVal Level As Long, pPrinter As Any, ByVal Command As Long) As Long
    Private Declare Function GetPrinter Lib "winspool.drv" Alias "GetPrinterA" (ByVal hPrinter As Long, ByVal Level As Long, pPrinter As Any, ByVal cbBuf As Long, pcbNeeded As Long) As Long
    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (hpvDest As Any, hpvSource As Any, ByVal cbCopy As Long)
    Private Declare Function ClosePrinter Lib "winspool.drv" (ByVal hPrinter As Long) As Long'The following is an unusual declaration of DocumentProperties:
    '  pDevModeOutput and pDevModeInput are usually declared ByRef.  They are declared
    '  ByVal in this program because we're using a Printer_Info_2 structure.
    '  The pi2 structure contains a variable of type LONG which contains the address
    '  of the DevMode structure (this is called a pointer).  This LONG variable must
    '  be passed ByVal.
    '  Normally this function is called with a BYTE ARRAY which contains the DevMode
    '  structure and the Byte Array is passed ByRef.
    Private Declare Function DocumentProperties Lib "winspool.drv" Alias "DocumentPropertiesA" (ByVal hWnd As Long, ByVal hPrinter As Long, ByVal pDeviceName As String, ByVal pDevModeOutput As Any, ByVal pDevModeInput As Any, ByVal fMode As Long) As LongPrivate Sub SetOrientation(NewSetting As Long, chng As Integer, ByVal frm As Form)
        Dim PrinterHandle As Long
        Dim PrinterName As String
        Dim pd As PRINTER_DEFAULTS
        Dim MyDevMode As DEVMODE
        Dim Result As Long
        Dim Needed As Long
        Dim pFullDevMode As Long
        Dim pi2_buffer() As Long     'This is a block of memory for the Printer_Info_2 structure
            'If you need to use the Printer_Info_2 User Defined Type, the
            '  definition of Printer_Info_2 in the API viewer is incorrect.
            '  pDevMode and pSecurityDescriptor should be defined As Long.
        
        PrinterName = Printer.DeviceName
        If PrinterName = "" Then
            Exit Sub
        End If
        
        pd.pDatatype = vbNullString
        pd.pDevMode = 0&
        'Printer_Access_All is required for NT security
        pd.DesiredAccess = PRINTER_ALL_ACCESS
        
        Result = OpenPrinter(PrinterName, PrinterHandle, pd)
        
        'The first call to GetPrinter gets the size, in bytes, of the buffer needed.
        'This value is divided by 4 since each element of pi2_buffer is a long.
        Result = GetPrinter(PrinterHandle, 2, ByVal 0&, 0, Needed)
        ReDim pi2_buffer((Needed \ 4))
        Result = GetPrinter(PrinterHandle, 2, pi2_buffer(0), Needed, Needed)
        
        'The seventh element of pi2_buffer is a Pointer to a block of memory
        '  which contains the full DevMode (including the PRIVATE portion).
        pFullDevMode = pi2_buffer(7)
        
        'Copy the Public portion of FullDevMode into our DevMode structure
        Call CopyMemory(MyDevMode, ByVal pFullDevMode, Len(MyDevMode))
        
        'Make desired changes
        MyDevMode.dmDuplex = NewSetting
        MyDevMode.dmFields = DM_DUPLEX Or DM_ORIENTATION
        MyDevMode.dmOrientation = chng
        
        'Copy our DevMode structure back into FullDevMode
        Call CopyMemory(ByVal pFullDevMode, MyDevMode, Len(MyDevMode))
        
        'Copy our changes to "the PUBLIC portion of the DevMode" into "the PRIVATE portion of the DevMode"
        Result = DocumentProperties(frm.hWnd, PrinterHandle, PrinterName, ByVal pFullDevMode, ByVal pFullDevMode, DM_IN_BUFFER Or DM_OUT_BUFFER)
        
        'Update the printer's default properties (to verify, go to the Printer folder
        '  and check the properties for the printer)
        Result = SetPrinter(PrinterHandle, 2, pi2_buffer(0), 0&)
        
        Call ClosePrinter(PrinterHandle)
        
        'Note: Once "Set Printer = " is executed, anywhere in the code, after that point
        '      changes made with SetPrinter will ONLY affect the system-wide printer  --
        '      -- the changes will NOT affect the VB printer object.
        '      Therefore, it may be necessary to reset the printer object's parameters to
        '      those chosen in the devmode.
        Dim p As Printer
        For Each p In Printers
            If p.DeviceName = PrinterName Then
                Set Printer = p
                Exit For
            End If
        Next p
        Printer.Duplex = MyDevMode.dmDuplex
    End SubPublic Sub ChngPrinterOrientationLandscape(ByVal frm As Form)
        PageDirection = 2
        Call SetOrientation(DMDUP_SIMPLEX, PageDirection, frm)
    End SubPublic Sub ResetPrinterOrientation(ByVal frm As Form)
     
        If PageDirection = 1 Then
            PageDirection = 2
        Else
            PageDirection = 1
        End If
        Call SetOrientation(DMDUP_SIMPLEX, PageDirection, frm)
    End SubPublic Sub ChngPrinterOrientationPortrait(ByVal frm As Form)    PageDirection = 1
        Call SetOrientation(DMDUP_SIMPLEX, PageDirection, frm)
    End Sub
      

  3.   

    Option Explicit
    '***************************************************************
    '设置默认打印方向功能模块     Programming:ztchen   2002.5
    '用于设置默认打印机的打印方向
    '***************************************************************
    '可使用的枚举参数,代表打印方向
    Public Enum PrinterOrientationConstants
        OrientPortrait = 1      '纵向
        OrientLandscape = 2     '横向
    End Enum'打印机设备设置的信息
    Private Type DEVMODE
        dmDeviceName As String * 32
        dmSpecVersion As Integer
        dmDriverVersion As Integer
        dmSize As Integer
        dmDriverExtra As Integer
        dmFields As Long
        dmOrientation As Integer
        dmPaperSize As Integer
        dmPaperLength As Integer
        dmPaperWidth As Integer
        dmScale As Integer
        dmCopies As Integer
        dmDefaultSource As Integer
        dmPrintQuality As Integer
        dmColor As Integer
        dmDuplex As Integer
        dmYResolution As Integer
        dmTTOption As Integer
        dmCollate As Integer
        dmFormName As String * 32
        dmUnusedPadding As Integer
        dmBitsPerPel As Integer
        dmPelsWidth As Long
        dmPelsHeight As Long
        dmDisplayFlags As Long
        dmDisplayFrequency As Long
    End Type
    '该结构的dmFields成员的定义值之一
    '用于与成员对应的属性的初始设置
    Private Const DM_ORIENTATION = &H1      '打印方向'打印机的默认信息
    Private Type PRINTER_DEFAULTS
        pDataType As String
        pDevMode As Long
        DesiredAccess As Long
    End Type
    '该结构的DesiredAccess成员定义
    '用于设置打印机的可访问权限
    Private Const PRINTER_ACCESS_ADMINISTER = &H4   '管理员级访问权限
    Private Const PRINTER_ACCESS_USE = &H8          '普通用户级访问权限
    Private Const STANDARD_RIGHTS_REQUIRED = &HF0000    '标准访问需要
    Private Const PRINTER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED Or _
        PRINTER_ACCESS_ADMINISTER Or PRINTER_ACCESS_USE)    '所有访问权限'打印机的详细信息
    Private Type PRINTER_INFO_2
        pServerName As Long
        pPrinterName As Long
        pShareName As Long
        pPortName As Long
        pDriverName As Long
        pComment As Long
        pLocation As Long
        pDevMode As Long
        pSepFile As Long
        pPrintProcessor As Long
        pDataType As Long
        pParameters As Long
        pSecurityDescriptor As Long
        Attributes As Long
        Priority As Long
        DefaultPriority As Long
        StartTime As Long
        UntilTime As Long
        Status As Long
        cJobs As Long
        AveragePPM As Long
    End Type'内存拷贝
    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
        (hpvDest As Any, hpvSource As Any, ByVal cbCopy As Long)'打开打印机以操作
    Private Declare Function OpenPrinter Lib "winspool.drv" Alias _
        "OpenPrinterA" (ByVal pPrinterName As String, phPrinter As _
        Long, pDefault As Any) As Long
        
    '返回打印机信息
    Private Declare Function GetPrinter Lib "winspool.drv" _
        Alias "GetPrinterA" (ByVal hPrinter As Long, ByVal Level As Long, _
        pPrinter As Any, ByVal cbBuf As Long, pcbNeeded As Long) As Long'设置打印机设置数据及控制打印机操作状态
    Private Declare Function SetPrinter Lib "winspool.drv" _
        Alias "SetPrinterA" (ByVal hPrinter As Long, ByVal Level As Long, _
        pPrinter As Any, ByVal Command As Long) As Long'关闭打印机
    Private Declare Function ClosePrinter Lib "winspool.drv" _
        (ByVal hPrinter As Long) As Long'返回或修改打印机初始信息和显示一个打印机设置对话框
    Private Declare Function DocumentProperties Lib "winspool.drv" _
        Alias "DocumentPropertiesA" (ByVal hWnd As Long, ByVal hPrinter As Long, _
        ByVal pDeviceName As String, pDevModeOutput As Any, pDevModeInput As Any, _
        ByVal fMode As Long) As Long
        
    '用于指定该函数操作的方式
    Private Const DM_IN_BUFFER = 8       '进行输入操作
    Private Const DM_OUT_BUFFER = 2      '进行输出操作Public Const ERR_NOPRINTER = "尚未安装打印机。如需安装打印机,请指向Windows“开始”菜单的“设置”,单击“打印机”,然后双击“添加打印机”。按照向导中的说明进行操作即可。"
    '设置默认打印机的打印方向
    'mp_Orientation:指定打印方向,默认为纵向
    '成功返回True,不成功返回False
    Public Function SetDefaultPrinterOrientation(Optional ByVal mp_Orientation As PrinterOrientationConstants = 1) As Boolean    Dim bytDevMode() As Byte        '开辟内存以保存打印机设置信息
    '    Dim lngOrgOrient As Long        '保存原先打印机设置的打印方向
        Dim bytPrinterInfo2() As Byte   '开辟内存以保存打印机详细设置
        Dim hPrinter As Long            '打印机的句柄
        Dim lResult As Long             '检测返回结果
        Dim nSize As Long               '缓冲区大小
        Dim strPrnName As String        '打印设备名
        Dim dm As DEVMODE               '打印机设置信息
        Dim pd As PRINTER_DEFAULTS      '默认打印机信息
        Dim pi2 As PRINTER_INFO_2       '打印机详细信息    '获取默认打印机的设备名
        On Error GoTo Err_Hld
        strPrnName = Printer.DeviceName
        '设置访问打印机所有权限以在NT下能进行访问
        pd.DesiredAccess = PRINTER_ALL_ACCESS    '打开打印机并获取一个打印机句柄
        If OpenPrinter(strPrnName, hPrinter, pd) Then
            '实验并获取当前打印机所需要的缓冲区大小
            GetPrinter hPrinter, 2&, 0&, 0&, nSize
            '根据所获得的缓冲区大小重新分配需要存放打印机详细设置的内存大小
            ReDim bytPrinterInfo2(nSize) As Byte
            '返回打印机详细信息到所开辟的内存中
            lResult = GetPrinter(hPrinter, 2, bytPrinterInfo2(0), _
                nSize, nSize)
            '执行失败则退出
            If lResult = 0 Then
                SetDefaultPrinterOrientation = False
                ClosePrinter hPrinter
                Exit Function
            End If
            '拷贝打印机详细信息的内容到打印机详细信息结构体
            CopyMemory pi2, bytPrinterInfo2(0), Len(pi2)        '获取打印机设置信息的缓冲区大小
            nSize = DocumentProperties(0, hPrinter, strPrnName, 0, 0, 0)
            '根据获得的打印机设置信息缓冲区大小分配相应的内存
            ReDim bytDevMode(nSize)
            
            If pi2.pDevMode Then
                '如果打印机详细信息结构中的pDevMode成员,
                '即打印机设置信息不为空则将其内容拷贝到所开辟的存放打印机设置信息的内存中
                '为了操作安全性,拷贝时一定要在pi2.pDevMode上加上ByVal的限制,因为这是个不允许随意改变的指针
                CopayMemory bytDevMode(0), ByVal pi2.pDevMode, Len(dm)
            Else
                '如果为空则使用DocumentProperties函数直接输出打印机设置信息到所开辟的内存中
                DocumentProperties 0&, hPrinter, strPrnName, bytDevMode(0), 0&, DM_OUT_BUFFER
            End If
            '拷贝打印机设置信息内容到打印机设置信息结构体
            CopyMemory dm, bytDevMode(0), Len(dm)
            With dm
                '这里进行新方向的设置
                .dmOrientation = mp_Orientation
                .dmFields = DM_ORIENTATION
            End With
            '将新设置好的打印机设置信息拷贝回打印机设置信息内存
            CopyMemory bytDevMode(0), dm, Len(dm)
            
            '将新的打印机设置信息设置到打印机初始信息中
            DocumentProperties 0&, hPrinter, strPrnName, bytDevMode(0), _
            bytDevMode(0), DM_IN_BUFFER Or DM_OUT_BUFFER        '将打印机设置信息内存中的内容赋给打印印机详细信息结构的pDevMode成员
            '这里需要将该内存的地址传给其成员,因为成员pDevMode是一个指向打印机设置信息结构的内存
            pi2.pDevMode = VarPtr(bytDevMode(0))
            
            '用新设置的打印机详细信息对打印机进行设置
            lResult = SetPrinter(hPrinter, 2, pi2, 0&)
            If lResult = 0 Then
                SetDefaultPrinterOrientation = False
                ClosePrinter hPrinter
                Exit Function
            End If
            
            '操作完后关闭打印机并返回成功
            Call ClosePrinter(hPrinter)
            SetDefaultPrinterOrientation = True
        Else
            '打开打印机失败则返回失败
            SetDefaultPrinterOrientation = False
        End If
        Exit Function
    Err_Hld:
        '没有安装打印机错误
        If Err.Number = 484 Then
            MsgBox ERR_NOPRINTER, vbExclamation, "打印机错误"
            SetDefaultPrinterOrientation = False
            Exit Function
        End If
    End Function