VB6: List all printers using code in Windows

Listing all printers with name, Port in VB6 is simple as listing default printer port using Kernel32 library . Today we going show you how to do this.

As usual we start with function declaration, then define a new function which add all information into a list box. Here we goes

Kernel32 GetProfileString method

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

Add printer information into a list box

Public Sub GetPrinterList(lstPrinter As ListBox)
Dim PrintData As Printer
Dim defprinterpos%
For Each PrintData In Printers
‘ Add printer name and port to list
lstPrinter.AddItem PrintData.DeviceName & ” at: ” & PrintData.Port
‘ Check for default printer
If PrintData.DeviceName = Printer.DeviceName Then defprinterpos = lstPrinter.NewIndex
lstPrinter.ListIndex = defprinterpos%
End Sub

This sub procedure will take list box as argument, and add printer to this list box.

Call the sub

The final line of code just invoke the procedure and see what we have. 
Happy coding

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
    ‘ 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

How to get Computer Name using VB6 Code

Accessing system property is pretty easy with VB6 code. This can be useful when programmers need to refer the system name in the code.


  • Declare the GetComputerNameA function which resides in the kernel32 library
  • Create function to fetch the Computer Name.
  • Use the function

The Kernel function

 Declare Function GetComputerNameA Lib “kernel32” (ByVal lpBuffer As String, nSize As Long) As Long

Get the computer name

Public Function GetComputerName() As String
Dim sResult As String * 255
GetComputerNameA sResult, 255
GetComputerName = Left$(sResult, InStr(sResult, Chr$(0)) – 1)
End Function

Calling the function

Text1.Text = GetComputerName

Expensive strings and stringBuilder class in C#

As we know strings are a group of characters, usually composed of letters, numerals and special symbols etc. C# string type is immutable  object, i.e, they can be created once, after that they can’t be modified.

Diagnostic Tools in C#

Immutable string

Usually you may argue that it is a non sense, I am talking about. Let’s consider the following line of code

string str=” Some string” 

str+=” Some other string” 

Here firstly we created  string variable str and add some initial string value and trying to add  new string “Some other string” with the old one. Even Though there is + operator appeared after the variable, the string variable can’t be modified, instead C# will create a new string by combining the both strings. As a result more and more memory occupied.

Build mutable strings with StringBuilder

This problem can be simply fixed with in built C# class StringBuilder which is mutable object. Following example will clarify the  idea. Create a console application which will execute a series of sample string for a specific times, say 1000.

            string str=””;
for(int i = 0; i <= 10000; i++)
str += “Sample C# string”;
Console.WriteLine(“String numbers are:” + str);

Above code will result in extravagant use of memory and may slash the speed of the program, by using the string builder, it can be rewritten as ,

            string str=””;
StringBuilder sb = new StringBuilder() ;
for(int i = 0; i <= 10000; i++)
sb.Append (” Sample C# strings “);
str = sb.ToString();
Console.WriteLine(“String numbers are:” + str);

Open the Diagnostic Tool in Visual Studio 2013/15 to find out memory usage. As the program get more complex you can find out that StringBuilder uses less memory than immutable  string. StringBuilder also come with

Auto complete TextBox in C#

An Autocomplete Textbox is a must have for a commercial application, it can bring user friendly features to you application.
Lets learn how to add a Auto complete feature, here is the plan

Code poet’s steps

  1. First we make up the Autocomplete string collection.
    1. Create AutoCompleteStringCollection
    2. Add items to the collection.
  2. Set Autocomplete mode
  3. Set Auto complete source as custom source
  4. Set auto complete custom source as Autocomplete string collection.
  5. That is all


AutoCompleteStringCollection a = new AutoCompleteStringCollection();
            a.Add(“Ice Bowl”);
            textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
            textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
            textBox1.AutoCompleteCustomSource = a;

As you see you can just type the letters Man  and a new list will populate, as result of the AutoCompleteMode.Suggest code, can replace it with append or appendSuggest which will automatically complete text as you type.

Create Table at run time using DAO connection in Visual Basic 6.0

Using VB6 database connection (DAO) connection we can not only manipulate data from the existing database but also dynamically create new table according to the necessity of the program. This can be achieved using CreateTableDef method of record set object.

Make sure your are included the appropriate references from References window.

Create a new connection 

Dim MedicalShop as Database
Set MedicalShop=opendatabse(GetAppPath()& “shop.mdb”)

Create the Sub for create table

The the sub will utilizes the Tabledef and Fields objects and by using the CreateTabledef command it will create the new table.

Lets add the body of the procedure as follows

Public Sub CreateTable(tbl As String, fl() As String)
Dim tdf As TableDef
Dim fld As Field
Dim f, I
I = 0
Set tdf = MedicalShop.CreateTableDef(tbl)
For Each f In fl
 If f Empty Then
  Set fld = tdf.CreateField(f, dbText)
  tdf.Fields.Append fld
  I = I + 1
 End If
MedicalShop.TableDefs.Append tdf
End Sub

By default the field type is DbText, you can specify each  with different type by passing an addition argument list or a two dimensional array.

Call the CreateTable method

Dim f(3) as String

Now call the procedure

Call CreateTable(“salesentry”,f)

Will create a new table with fields and having Text field type.

Pause execution for few seconds in VB6

Timers control is familiar control in Visual Basic 6.0 which enable programmer to execute code within a specified intervals. But what you do when y want to keep computer delaying execution for few minutes/seconds? Here is the solution.
With the Timer object your can do this trick. Create a Sub to perform the delay operations.

Sub Pause(interval)
Current = Timer
Do While Timer – Current < Val(interval)
End Sub 
Now call the Pause() with delay time as seconds
call Pause (1)  ‘will delay execution of statements for few seconds

How to get access to all column names of table in VB.Net/ADO.net

Using ‘getSchema’ method we can access database properties such as Column names, Tables name etc. ,with some tricky code in Visual Basic.Net . Here is how you can access all columns names in a Access table with OLEDB connection in VB ADO.net 2013.

Sub AddListViewColumsAuto( tbl As String)
Dim Company As OleDb.OleDbConnection
 Company = New OleDb.OleDbConnection
 Company.ConnectionString = “Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\.Net  Project\Accounting Pack\AccountingPack.accdb”
 Dim cmd As New OleDb.OleDbCommand(“Select * from ” & tbl, Company)
 Dim columns As String = “Columns”
 Dim dt As DataTable = Company.GetSchema(columns)
For Each row As DataRow In dt.Rows
End Sub


First we create connection object, Company and a connection string. Then we need a OleDb.OleDbCommand object to set database to point a particular table, so that we created the cmd object and used it for query the input table.


In the next stage we created a column string in order to point Columns in the table. Using Getschema() method of connection object Company we stored each and every column name in the connection to the table variable dt.


In the final step we can access all rows from the dt which contain column names from table dt using COLUMN_NAME  field.

Here is the video tutorial of how you can access and add column names to the console.

Clear and Format all textboxes at runtime in Visual Basic

All we know Visual Basic 6 is the simplest ways to develop Windows application for desktop computer. In this special article we are going to learn a code poem which automatically clear the text box content with few line of code. The idea sound good, isn’t it?

Firstly lets make a Sub to clear the fields. I have two method the first one let you clear selected text box which utilize the paramArray argument and the second will clear the entire field in a form. 
Open your Visual Basic 6.0 and enter the following sub routine.

Sub ClearBox for selected boxes

Sub ClearBox (ParamArray boxes() As Variant)
Dim ct As Variant
For Each ct In boxes
 If TypeOf ct Is TextBox Then
    ct.Text = “”
 End If
End Sub

This sub will clear the passed text box controls  on the form,  The sub utilizes the paramArray feature, so that the program can accept any number of arguments/controls. Remember that paramArray object should be type of variant.

Clear all the boxes

The second method will clear all the boxes on the form. Lets take a look at the second code. 

Sub ClearBox_Auto(f As  Form)
 Dim ob As Object
 Dim ct As Control

 For Each ob In Form1.Controls
  Set ct = ob
  If TypeOf ct Is TextBox Then
    ct.Text = “”
  End If
 End Sub

Form’s controls property is returning the object collection and we collect each of then to ‘ob’ and then assign to a control variable and then can do the similar type of operations done in Clear Box. sub

Auto Number Format ‘Sub’

Finally I have a special format box which  utilise Forms controls collection to gather controls appeared in the User Interface and  apply specific number format to all the number field as follows.

Sub AutoNumberFormat(f As  Form)
 Dim ob As Object
 Dim ct As Control

 For Each ob In Form1.Controls
  Set ct = ob
  If TypeOf ct Is TextBox Then
     If IsNumeric(ct.Text) Then
        ct.Text = Format(ct, “0.00”)
     End If
  End If

End Sub

Call the Box function

Let invoke the subroutines on the click event of command button 
‘Clear selected boxes
 Call ClearBox(TextBox1, TextBox2, TextBox3)
‘Clear All the boxes
Call ClearBox_Auto(Me)

‘Format numbered fields
Call AutoNumberFormat(Me)


The code is working on Microsoft Word VBA and Visual Studio 6.0   alike. For using on Word VBA please replace the Form (in argument) with UserForm

 Join us on Disqus.