VB6: List default printer using code in Windows


kernel32 hold lots of interesting function that you may not utilized yet. With the Profile String  functionality programmers can list default printer name, with serial port, Driver etc. Is that interesting. 


Just create a bunch of function and call it.

Declare the function

Declare Function GetProfileString Lib “kernel32.dll” Alias “GetProfileStringA” (ByVal lpAppName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long) As Long

Define the GetDefaultPrinter function

Public Function GetDefaultPrinter() As Printer
    Dim strBuffer As String * 254
    Dim iRetValue As Long
    Dim strDefaultPrinterInfo As String
    Dim tblDefaultPrinterInfo() As String
    Dim objPrinter As Printer
    ‘ Retreive current default printer information
    iRetValue = GetProfileString(“windows”, “device”, “,,,”, strBuffer, 254)
    strDefaultPrinterInfo = Left(strBuffer, InStr(strBuffer, Chr(0)) – 1)
    tblDefaultPrinterInfo = Split(strDefaultPrinterInfo, “,”)
    For Each objPrinter In Printers
        If objPrinter.DeviceName = tblDefaultPrinterInfo(0) Then
            ‘ Default printer found !
            Exit For
        End If
    Next
    ‘ If not found, return nothing
    If objPrinter.DeviceName tblDefaultPrinterInfo(0) Then
        Set objPrinter = Nothing
    End If
    Set GetDefaultPrinter = objPrinter
End Function

Use the function to list default  

Private Sub Command8_Click()
Dim objPrinter As Printer
Set objPrinter = GetDefaultPrinter()
Text2.Text = “Default printer is: ” + objPrinter.DeviceName & _
Chr(13) & ” Driver name is: ” + objPrinter.DriverName _
& Chr(13) & ” Port is: ” + objPrinter.Port
Set objPrinter = Nothing
End Sub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.