Solved

set printer

Posted on 1998-09-09
4
523 Views
Last Modified: 2008-03-04
I want to catch and restore the default printer from the
common dialog box after the user has finished printing to
a second printer.  Please see my code example:

Dim p As Printer
Dim OldPrinter As Printer

For Each p In Printers
    If p.DeviceName = Printer.DeviceName Then
        Debug.Print "loop "; p.DeviceName
       ' Set printer as system default.
        Set OldPrinter = p
        ' Stop looking for a printer.
        Exit For
    End If
Next

    OldFont = Printer.Font
    CommonDialog1.Flags = cdlPDPrintSetup
    CommonDialog1.Flags = cdlPDHidePrintToFile
    CommonDialog1.PrinterDefault = True
    On Error Resume Next
    CommonDialog1.CancelError = True
    CommonDialog1.ShowPrinter
    If Err.Number = cdlCancel Then
      Exit Sub
    Else
      If Err.Number <> 0 Then
        MsgBox Err.Description
      End If
    End If
    On Error GoTo 0
    .
    .
Printer.EndDoc
Set Printer = OldPrinter
Debug.Print "set printer "; Printer.DeviceName
Printer.FontName = OldFont

The immidiate window shows me that I am finding the default
printer and then resetting it after EndDoc.  However, when
I select print again or exit the window and come back, the
printer is the last printer selected not the default I
set with set printer.  I'm a newbie, thanks for any help.
0
Comment
Question by:JodiC
  • 3
4 Comments
 
LVL 14

Accepted Solution

by:
waty earned 50 total points
ID: 1433839
It is a known bug in VB5.
Use one of the following function :

Option Explicit

Declare Function GetProfileString Lib "kernel32" Alias "GetProfileStringA" (ByVal lpAppName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long) As Long
Declare Function WriteProfileString Lib "kernel32" Alias "WriteProfileStringA" (ByVal lpszSection As String, ByVal lpszKeyName As String, ByVal lpszString As String) As Long
Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lparam As String) As Long

Public Const HWND_BROADCAST = &HFFFF
Public Const WM_WININICHANGE = &H1A

Public Type OSVERSIONINFO
   dwOSVersionInfoSize  As Long
   dwMajorVersion       As Long
   dwMinorVersion       As Long
   dwBuildNumber        As Long
   dwPlatformId         As Long
   szCSDVersion         As String * 128
End Type

Public Declare Function GetVersionExA Lib "kernel32" (lpVersionInformation As OSVERSIONINFO) As Integer
Public Declare Function OpenPrinter Lib "winspool.drv" Alias "OpenPrinterA" (ByVal pPrinterName As String, phPrinter As Long, pDefault As PRINTER_DEFAULTS) As Long
Public 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
Public 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
Public Declare Function lstrcpy Lib "kernel32" Alias "lstrcpyA" (ByVal lpString1 As String, ByVal lpString2 As Any) As Long
Public Declare Function ClosePrinter Lib "winspool.drv" (ByVal hPrinter As Long) As Long
Public Declare Function GetLastError Lib "kernel32" () As Long

' *** constants for DEVMODE structure
Public Const CCHDEVICENAME = 32
Public Const CCHFORMNAME = 32

' *** constants for DesiredAccess member of PRINTER_DEFAULTS
Public Const STANDARD_RIGHTS_REQUIRED = &HF0000
Public Const PRINTER_ACCESS_ADMINISTER = &H4
Public Const PRINTER_ACCESS_USE = &H8
Public Const PRINTER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED Or PRINTER_ACCESS_ADMINISTER Or PRINTER_ACCESS_USE)

' *** constant that goes into PRINTER_INFO_5 Attributes member to set it as default
Public Const PRINTER_ATTRIBUTE_DEFAULT = 4

Public 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 Type

Public Type PRINTER_INFO_5
   pPrinterName               As String
   pPortName                  As String
   Attributes                 As Long
   DeviceNotSelectedTimeout   As Long
   TransmissionRetryTimeout   As Long
End Type

Public Type PRINTER_DEFAULTS
   pDatatype            As Long
   pDevMode             As DEVMODE
   DesiredAccess        As Long
End Type

Declare Function SetBkColor Lib "gdi32" (ByVal hdc As Long, ByVal crColor As Long) As Long

Private Function PtrCtoVbString(Add As Long) As String
   
   Dim sTemp As String * 512, x As Long
   
   x = lstrcpy(sTemp, Add)
   If (InStr(1, sTemp, Chr(0)) = 0) Then
      PtrCtoVbString = ""
   Else
      PtrCtoVbString = left(sTemp, InStr(1, sTemp, Chr(0)) - 1)
   End If

End Function

Public Sub SetDefaultPrinter(ByVal PrinterName As String, ByVal DriverName As String, ByVal PrinterPort As String)
   
   Dim DeviceLine As String
   Dim r As Long
   Dim l As Long
   DeviceLine = PrinterName & "," & DriverName & "," & PrinterPort
   ' *** Store the new printer information in the [WINDOWS] section of
   ' *** the WIN.INI file for the DEVICE= item
   r = WriteProfileString("windows", "Device", DeviceLine)
   
   ' *** Cause all applications to reload the INI file:
   l = SendMessage(HWND_BROADCAST, WM_WININICHANGE, 0, "windows")

End Sub

Public Sub Win95SetDefaultPrinter(sPrinter As String)
   
   Dim Handle           As Long              ' handle to printer
   Dim PrinterName      As String
   Dim pd               As PRINTER_DEFAULTS
   Dim x                As Long
   Dim need             As Long             ' bytes needed
   Dim pi5              As PRINTER_INFO_5   ' your PRINTER_INFO structure
   Dim LastError        As Long
   
   ' determine which printer was selected
   PrinterName = sPrinter
   
   ' none - exit
   If PrinterName = "" Then Exit Sub
   
   ' set the PRINTER_DEFAULTS members
   pd.pDatatype = 0&
   pd.DesiredAccess = PRINTER_ALL_ACCESS
   
   ' Get a handle to the printer
   x = OpenPrinter(PrinterName, Handle, pd)
   
   ' failed the open
   If x = False Then Exit Sub
     
   ' Make an initial call to GetPrinter, requesting Level 5  (PRINTER_INFO_5)
   ' information, to determine how many bytes  you need
   x = GetPrinter(Handle, 5, ByVal 0&, 0, need)
   
   ' don 't want to check GetLastError here - it's supposed to fail
   ' with a 122 - ERROR_INSUFFICIENT_BUFFER
   ' redim t as large as you need
   
   ReDim t((need \ 4)) As Long
   
   ' and call GetPrinter for keepers this time
   x = GetPrinter(Handle, 5, t(0), need, need)
   
   ' failed the GetPrinter
   If x = False Then Exit Sub
     
   ' set the members of the pi5 structure for use with SetPrinter.
   ' PtrCtoVbString copies the memory pointed at by the two    string
   ' pointers contained in the t() array into a Visual Basic string.
   ' The other three elements are just DWORDS (long integers) and
   ' don 't require any conversion
   pi5.pPrinterName = PtrCtoVbString(t(0))
   pi5.pPortName = PtrCtoVbString(t(1))
   pi5.Attributes = t(2)
   pi5.DeviceNotSelectedTimeout = t(3)
   pi5.TransmissionRetryTimeout = t(4)
   
   ' this is the critical flag that makes it the default printer
   pi5.Attributes = PRINTER_ATTRIBUTE_DEFAULT
   
   ' call SetPrinter to set it
   x = SetPrinter(Handle, 5, pi5, 0)
   
   ' failed the SetPrinter
   If x = False Then Exit Sub
   
   ' and close the handle
   ClosePrinter (Handle)
   
End Sub

Public Sub GetDriverAndPort(ByVal Buffer As String, DriverName As String, PrinterPort As String)
   
   Dim iDriver As Integer
   Dim iPort As Integer
   DriverName = ""
   PrinterPort = ""
   
   ' The driver name is first in the string terminated by a comma
   iDriver = InStr(Buffer, ",")
   
   If iDriver > 0 Then
      ' Strip out the driver name
      DriverName = left(Buffer, iDriver - 1)
   
      ' The port name is the second entry after the driver name separated by commas.
      iPort = InStr(iDriver + 1, Buffer, ",")
      If iPort > 0 Then
         ' Strip out the port name
         PrinterPort = Mid(Buffer, iDriver + 1, _
         iPort - iDriver - 1)
      End If
   End If

End Sub

Public Sub ParseList(lstCtl As Control, ByVal Buffer As String)
   
   Dim i As Integer
   
   lstCtl.Clear
   
   Do
      i = InStr(Buffer, Chr(0))
      If i > 0 Then
         If (Trim(left(Buffer, i - 1)) <> "") Then lstCtl.AddItem left(Buffer, i - 1)
         Buffer = Mid(Buffer, i + 1)
      Else
         If (Trim(Buffer) <> "") Then lstCtl.AddItem Buffer
         Buffer = ""
      End If
   Loop While i > 0

End Sub

Public Sub WinNTSetDefaultPrinter(sPrinter As String)
   
   Dim Buffer        As String
   Dim DeviceName    As String
   Dim DriverName    As String
   Dim PrinterPort   As String
   Dim PrinterName   As String
   Dim r             As Long
   
   Buffer = Space(1024)
   PrinterName = sPrinter
   r = GetProfileString("PrinterPorts", PrinterName, "", Buffer, Len(Buffer))
   
   ' Parse the driver name and port name out of the buffer
   GetDriverAndPort Buffer, DriverName, PrinterPort
   If DriverName <> "" And PrinterPort <> "" Then
      SetDefaultPrinter sPrinter, DriverName, PrinterPort
   End If

End Sub

0
 

Author Comment

by:JodiC
ID: 1433840
Well, yes that did save and reset the printer.  However, now
when I select a printer other than the default it does not print
to the selected printer.  That worked before, it does not now.
I have little doubt it is something I am doing.  Here's the code:

    PrinterName = Printer.DeviceName
    Debug.Print "printer name "; PrinterName
    OldFont = Printer.Font
    CommonDialog1.Flags = cdlPDPrintSetup
    CommonDialog1.Flags = cdlPDHidePrintToFile
    CommonDialog1.PrinterDefault = True
    On Error Resume Next
    CommonDialog1.CancelError = True
    CommonDialog1.ShowPrinter
    If Err.Number = cdlCancel Then
      Exit Sub
    Else
      If Err.Number <> 0 Then
        MsgBox Err.Description
      End If
    End If
    On Error GoTo 0
     
    Printer.FontName = "Courier New"
    Printer.Orientation = vbPRORPortrait
   
    Open Order_File For Input As #1
    Do While Not EOF(1)
       Line Input #1, Textline
       Printer.Print Textline
     Loop
     Close #1

Printer.EndDoc
Win95SetDefaultPrinter (PrinterName)
Debug.Print "set printer "; Printer.DeviceName
Printer.FontName = OldFont
Exit Sub





0
 

Author Comment

by:JodiC
ID: 1433841
It appears that the routine Waty sent me works just fine to set
the printer back.  The trouble I think the problem I am having
is that the printer does not change if I do not change the
selection in the dialog box.  That is if I leave the default
it is printing to the last selection even though the dialog box
is correct.  What must I do to set my printer to the selection
displayed or chosen from the dialog
0
 

Author Comment

by:JodiC
ID: 1433842
Waty's answer to my original question is correct.  I'm not sure
how to sink up the printer with the dialog selection still.  If
I exit the window and reenter it seems to work o.k.  That will
do for now.

Thanks for your help
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction While answering a recent question (http://www.experts-exchange.com/Q_27402310.html) in the VB classic zone, I wrote some VB code in the (Office) VBA environment, rather than fire up my older PC.  I didn't post completely correct code o…
When trying to find the cause of a problem in VBA or VB6 it's often valuable to know what procedures were executed prior to the error. You can use the Call Stack for that but it is often inadequate because it may show procedures you aren't intereste…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now