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 functions

Create the following functions and Alias which is the prerequisite for our program.

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

Let create our custom functions for fetching the default printer.

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

Using the function to list default

Drag and drop a command button and a Text Box to your form and drop these code into click event of the button.

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

Lets run and see what going on

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.