Solved

Install or Rename a Printer

Posted on 2003-12-09
16
712 Views
Last Modified: 2009-07-29
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
Comment
Question by:Dwhite
  • 8
  • 5
  • 2
16 Comments
 
LVL 5

Expert Comment

by:mccainz2
ID: 9903595
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
 
LVL 5

Accepted Solution

by:
mccainz2 earned 250 total points
ID: 9903653
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
 
LVL 5

Expert Comment

by:mccainz2
ID: 9903855
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
 
LVL 5

Expert Comment

by:mccainz2
ID: 9904115
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
 
LVL 5

Expert Comment

by:mccainz2
ID: 9904156
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
 

Author Comment

by:Dwhite
ID: 9904303
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
 

Author Comment

by:Dwhite
ID: 9904333
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 5

Expert Comment

by:mccainz2
ID: 9904440
WHat OS and what level (user/admin/etc) are you running the script as ?
0
 

Author Comment

by:Dwhite
ID: 9904545
Its on w2000 on an Administrator account.
0
 
LVL 5

Expert Comment

by:mccainz2
ID: 9904759
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
 
LVL 5

Expert Comment

by:mccainz2
ID: 9905000
renmaePrinter method implemented in the july 2003 platform sdk release..... that would explain it....
0
 
LVL 27

Expert Comment

by:planocz
ID: 10279922
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
 

Author Comment

by:Dwhite
ID: 10279980
This Issue was never resolved but if you feel he deserves the points for his input the thats OK by me.
0
 
LVL 27

Expert Comment

by:planocz
ID: 10280066
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
 

Author Comment

by:Dwhite
ID: 10280108
Great thank you.
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 about filtering a custom class collection, I realized that this could be accomplished with very little code by using the ScriptControl (SC) library.  This article will introduce you to the SC library a…
Background What I'm presenting in this article is the result of 2 conditions in my work area: We have a SQL Server production environment but no development or test environment; andWe have an MS Access front end using tables in SQL Server but we a…
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
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…

760 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

16 Experts available now in Live!

Get 1:1 Help Now