Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 747
  • Last Modified:

Install or Rename a Printer

Hi all
Is there a way to either Install or Rename a Printer with VB Code.
Any help would be much appreciated.
Thank You,
Dean White.
0
Dwhite
Asked:
Dwhite
  • 8
  • 5
  • 2
1 Solution
 
mccainz2Commented:
You can utilize the WSH scripting host reference for these tasks....(add the ref to your project)

There are also functions for handling network printers also ...

 Dim objWshN As New WshNetwork
   

objWshN.RemovePrinterConnection .....
objWshN.AddPrinterConnection .....
0
 
mccainz2Commented:
few fleshed out examples from MSDN

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/wsmthremoveprinterconnection.asp  (check out the see-also section for more)

The RemovePrinterConnection method removes both Windows and MS-DOS based printer connections. If the printer was connected using the method AddPrinterConnection, strName must be the printer's local name. If the printer was connected using the AddWindowsPrinterConnection method or was added manually (using the Add Printer wizard), then strName must be the printer's UNC name.


PrinterPath = "\\printserv\DefaultPrinter"
WshNetwork.RemovePrinterConnection PrinterPath, true, true


The AddPrinterConnection method adds a network printer to an MS-DOS printer port, such as LPT1. You cannot use this method to add a remote Windows-based printer connection. To add a remote Windows-based printer connection, use the AddWindowsPrinterConnection method.

................................

Set WshNetwork = WScript.CreateObject("WScript.Network")
WshNetwork.AddPrinterConnection "LPT1", "\\Server\Print1"
0
 
mccainz2Commented:
BTW: in vb you won't need to declare as  'Set WshNetwork = WScript.CreateObject("WScript.Network")'
Rather...
'Dim objWshN As New WshNetwork' will suffice
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
mccainz2Commented:
Worked out how to rename a printer , tested it here and it works well on XP\

Dim System As Object
    Set printerset = GetObject("winmgmts:").InstancesOf("Win32_Printer")
   
    For Each System In printerset
        Debug.Print System.Name
        If System.Name = "SnagIt 7" Then
            System.RenamePrinter ("SnagIt 9")
        End If
    Next
0
 
mccainz2Commented:
Running on 2000 or distributing the app will neccesitate you download and install the WMI redistributable...XP has this native.

http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=013BB284-3946-44A9-AC3C-BF2A569EAA72
0
 
DwhiteAuthor Commented:
Hi mccainz2
Thanks but when I run it I get an error.
"Object does not support this property or method"
on line
System.RenamePrinter ("NewName")
It loops through and lists the printers but wont rename it when it finds the it.

Dim System As Object
    Set printerset = GetObject("winmgmts:").InstancesOf("Win32_Printer")
   
    For Each System In printerset
        Debug.Print System.Name
        If System.Name = "Lexmark Optra T614" Then
            System.RenamePrinter ("NewName")
        End If
    Next
0
 
DwhiteAuthor Commented:
Can anyone maybe help to modify this code to change the printer name.


'****************************************************************
' Change Default Printer Class
'
' Description:
'   This class is used to change the default printer installed
'   on the system.  Refer to your Win32 documentation for more
'   information on these function.
'
' Author:
'   Richard Cardarelle, Eclipse Applications
'   rick@eclipseapplications.com
'   http://www.eclipseapplications.com
'
' You are free to modify this class from its original content.
' If modifications are for an improvement, please contact the
' author with your changes.
'
'****************************************************************
' Copyright © 1999 Eclipse Applications
'****************************************************************
Option Explicit

Private Const PRINTER_ACCESS_ADMINISTER  As Long = &H4&
Private Const PRINTER_ACCESS_USE         As Long = &H8&
Private Const STANDARD_RIGHTS_REQUIRED   As Long = &HF0000
Private Const PRINTER_ALL_ACCESS         As Long = (STANDARD_RIGHTS_REQUIRED Or PRINTER_ACCESS_ADMINISTER Or PRINTER_ACCESS_USE)

Private Const HWND_BROADCAST             As Long = &HFFFF&
Private Const WM_WININICHANGE            As Long = &H1A&

Private Const PRINTER_ATTRIBUTE_DEFAULT  As Long = 4&

Private Type PRINTER_DEFAULTS
    pDatatype                            As Long
    pDevmode                             As Long
    DesiredAccess                        As Long
End Type

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

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

'Private Const VER_PLATFORM_WIN32s       As Long = 0&
Private Const VER_PLATFORM_WIN32_WINDOWS As Long = 1&
Private Const VER_PLATFORM_WIN32_NT      As Long = 2&

Private 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
Private Declare Function WriteProfileString Lib "kernel32" Alias "WriteProfileStringA" (ByVal lpszSection As String, ByVal lpszKeyName As String, ByVal lpszString As String) As Long
Private Declare Function SendMessageString Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As String) As Long
Private 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 Function lstrcpy Lib "kernel32" Alias "lstrcpyA" (ByVal lpString1 As String, ByVal lpString2 As Any) As Long
Private Declare Function ClosePrinter Lib "winspool.drv" (ByVal hPrinter As Long) As Long
Private Declare Function GetVersionEx Lib "kernel32" Alias "GetVersionExA" (lpVersionInformation As OSVERSIONINFO) As Long


Public Property Let DefaultPrinter(ByVal sPrinterName As String)
   
    If sPrinterName = "" Then Exit Property
   
    Dim osi As OSVERSIONINFO
   
    osi.dwOSVersionInfoSize = Len(osi)
    Call GetVersionEx(osi)
   
    Select Case osi.dwPlatformId
        Case VER_PLATFORM_WIN32_WINDOWS
            If (osi.dwMinorVersion >= 10) Then
                ' Win 98
                WinNT_SetDefaultPrinter sPrinterName
            Else
                ' Win 95
                Win95_SetDefaultPrinter sPrinterName
            End If
        Case VER_PLATFORM_WIN32_NT
            ' Win NT
            WinNT_SetDefaultPrinter sPrinterName
        Case Else
            MsgBox "Unknown windows version..."
    End Select

End Property

Public Property Get DefaultPrinter() As String
    DefaultPrinter = Printer.DeviceName
End Property

Private Sub WinNT_SetDefaultPrinter(sPrinterName As String)
    Dim sPrinterPort    As String
    Dim sDriverName     As String
    Dim sBuffer         As String
    Dim RetVal          As Long
    Dim iDriver         As Integer
    Dim iPort           As Integer
   
    sBuffer = Space$(1024)
    sDriverName = vbNullString
    sPrinterPort = vbNullString
   
    RetVal = GetProfileString("PrinterPorts", sPrinterName, vbNullString, sBuffer, Len(sBuffer))
   
    iDriver = InStr(sBuffer, ",")
    If (iDriver > 0) Then
       sDriverName = Left$(sBuffer, (iDriver - 1))
       iPort = InStr((iDriver + 1), sBuffer, ",")
       If (iPort > 0) Then
          sPrinterPort = Mid(sBuffer, (iDriver + 1), (iPort - iDriver - 1))
       End If
    End If
   
    If (sDriverName <> vbNullString) And (sPrinterPort <> vbNullString) Then
        Dim sLine   As String
        sLine = sPrinterName & "," & sDriverName & "," & sPrinterPort
        ' Store the new printer information in the [WINDOWS] section of
        ' the WIN.INI file for the DEVICE= item
        RetVal = WriteProfileString("windows", "Device", sLine)
        ' Cause all applications to reload the INI file:
        RetVal = SendMessageString(HWND_BROADCAST, WM_WININICHANGE, 0&, "windows")
    End If
End Sub

Private Sub Win95_SetDefaultPrinter(sPrinterName As String)
    Dim ResultBuffer()  As Long
    Dim hPrinter        As Long
    Dim lNeeded         As Long
    Dim RetVal          As Long
    Dim pi5             As PRINTER_INFO_5
    Dim pd              As PRINTER_DEFAULTS
 
    ' set the PRINTER_DEFAULTS members
    pd.pDatatype = 0&
    pd.DesiredAccess = PRINTER_ALL_ACCESS

    ' Get a handle to the printer
    RetVal = OpenPrinter(sPrinterName, hPrinter, pd)
   
    If (RetVal <> 0) Then
        ' Get buffer size
        RetVal = GetPrinter(hPrinter, 5&, ByVal 0&, 0&, lNeeded)
        ReDim ReturnBuffer((lNeeded \ 4)) As Long
       
        ' Populate buffer
        RetVal = GetPrinter(hPrinter, 5&, ResultBuffer(0), lNeeded, lNeeded)
       
        If (RetVal <> 0) Then
            pi5.pPrinterName = PtrCtoVbString(ResultBuffer(0))
            pi5.pPortName = PtrCtoVbString(ResultBuffer(1))
            pi5.Attributes = ResultBuffer(2)
            pi5.DeviceNotSelectedTimeout = ResultBuffer(3)
            pi5.TransmissionRetryTimeout = ResultBuffer(4)
       
            ' this is the critical flag that makes it the default printer
            pi5.Attributes = PRINTER_ATTRIBUTE_DEFAULT
       
            ' call SetPrinter to set it
            RetVal = SetPrinter(hPrinter, 5&, pi5, 0&)
           
            ' failed the SetPrinter
            If (RetVal = 0) Then MsgBox "SetPrinterFailed. Error code: " & Err.LastDllError
            ClosePrinter (hPrinter)
        End If
    End If

End Sub

Private Function PtrCtoVbString(sAdd As Long) As String
    Dim sTemp   As String * 512
    Dim RetVal  As Long
    RetVal = lstrcpy(sTemp, sAdd)
    If (InStr(1, sTemp, Chr(0)) = 0) Then
         PtrCtoVbString = vbNullString
    Else
         PtrCtoVbString = Left$(sTemp, (InStr(1, sTemp, Chr(0)) - 1))
    End If
End Function

Private Sub Command1_Click()
DefaultPrinter = "Lexmark Optra T614"
End Sub
0
 
mccainz2Commented:
WHat OS and what level (user/admin/etc) are you running the script as ?
0
 
DwhiteAuthor Commented:
Its on w2000 on an Administrator account.
0
 
mccainz2Commented:
Just tested on one of our 2k computers here and even with ensuring the reditributable waqs installed , the method threw the same error as you reported ...
Seems XP only or there may be a impersonation setting in the Moniker that might allow it?? Researching.
0
 
mccainz2Commented:
renmaePrinter method implemented in the july 2003 platform sdk release..... that would explain it....
0
 
planoczCommented:
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:
No response from Dwhite from 12/09/2003 comment
Award points to mccainz2 is recommend.
Please leave any comments here within the next seven days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

planocz
EE Cleanup Volunteer
0
 
DwhiteAuthor Commented:
This Issue was never resolved but if you feel he deserves the points for his input the thats OK by me.
0
 
planoczCommented:
I will leave a recommendation in the Cleanup topic area that this question is:
Split points to mccainz2  and Refund  to DWhite is recommend.
Please leave any comments here within the next seven days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

planocz
EE Cleanup Volunteer
0
 
DwhiteAuthor Commented:
Great thank you.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 8
  • 5
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now