Visual Basic

Visual Basic (VB) is the third-generation event-driven programming language and integrated development environment (IDE) from Microsoft for its COM programming model. VB is also considered a relatively easy to learn and use programming language, because of its graphical development features and BASIC heritage.

Visual Basic was derived from BASIC and enables the rapid application development (RAD) of graphical user interface (GUI) applications, access to databases using Data Access Objects, Remote Data Objects, or ActiveX Data Objects, and creation of ActiveX controls and objects. Scripting languages such as VBA and VBScript are syntactically similar to Visual Basic, but perform differently.

A programmer can put together an application using the components provided with Visual Basic itself. Programs written in Visual Basic can also use the Windows API, but doing so requires external function declarations.

The final release was version 6 in 1998. Microsoft's extended support ended in March 2008 and the designated successor was Visual Basic .NET (now known simply as Visual Basic).
Contents

Language features

Like the BASIC programming language, Visual Basic was designed to be easy to learn and use. The language not only allows programmers to create simple GUI applications, but can also develop complex applications. Programming in VB is a combination of visually arranging components or controls on a form, specifying attributes and actions of those components, and writing additional lines of code for more functionality. Since default attributes and actions are defined for the components, a simple program can be created without the programmer having to write many lines of code. Performance problems were experienced by earlier versions, but with faster computers and native code compilation this has become less of an issue.

Although programs can be compiled into native code executables from version 5 onwards, they still require the presence of runtime libraries of approximately 1 MB in size. This runtime is included by default in Windows 2000 and later, but for earlier versions of Windows like 95/98/NT it must be distributed together with the executable.

Forms are created using drag-and-drop techniques. A tool is used to place controls (e.g., text boxes, buttons, etc.) on the form (window). Controls have attributes and event handlers associated with them. Default values are provided when the control is created, but may be changed by the programmer. Many attribute values can be modified during run time based on user actions or changes in the environment, providing a dynamic application. For example, code can be inserted into the form resize event handler to reposition a control so that it remains centered on the form, expands to fill up the form, etc. By inserting code into the event handler for a keypress in a text box, the program can automatically translate the case of the text being entered, or even prevent certain characters from being inserted.

Visual Basic can create executables (EXE files), ActiveX controls, DLL files, but is primarily used to develop Windows applications and to interface database systems. Dialog boxes with less functionality can be used to provide pop-up capabilities. Controls provide the basic functionality of the application, while programmers can insert additional logic within the appropriate event handlers. For example, a drop-down combination box will automatically display its list and allow the user to select any element. An event handler is called when an item is selected, which can then execute additional code created by the programmer to perform some action based on which element was selected, such as populating a related list.

Alternatively, a Visual Basic component can have no user interface, and instead provide ActiveX objects to other programs via Component Object Model (COM). This allows for server-side processing or an add-in module.

The language is garbage collected using reference counting, has a large library of utility objects, and has basic object oriented support. Since the more common components are included in the default project template, the programmer seldom needs to specify additional libraries. Unlike many other programming languages, Visual Basic is generally not case sensitive, although it will transform keywords into a standard case configuration and force the case of variable names to conform to the case of the entry within the symbol table entry. String comparisons are case sensitive by default, but can be made case insensitive if so desired.

The Visual Basic compiler is shared with other Visual Studio languages (C, C++), but restrictions in the IDE do not allow the creation of some targets (Windows model DLL's) and threading models.

 

Characteristics present in Visual Basic

Visual Basic has the following traits which differ from C-derived languages:

    * Multiple assignment available in C language is not possible. A = B = C does not imply that the values of A, B and C are equalled. The boolean result of "Is B = C?" is stored in A. The result stored in A could therefore be false(0) or true(-1)
    * Boolean constant True has numeric value ?1.[3] This is because the Boolean data type is stored as a 16-bit signed integer. In this construct ?1 evaluates to 16 binary 1s (the Boolean value True), and 0 as 16 0s (the Boolean value False). This is apparent when performing a Not operation on a 16 bit signed integer value 0 which will return the integer value ?1, in other words True = Not False. This inherent functionality becomes especially useful when performing logical operations on the individual bits of an integer such as And, Or, Xor and Not.[4] This definition of True is also consistent with BASIC since the early 1970s Microsoft BASIC implementation and is also related to the characteristics of CPU instructions at the time.
    * Logical and bitwise operators are unified. This is unlike some C-derived languages (such as Perl), which have separate logical and bitwise operators. This again is a traditional feature of BASIC.
    * Variable array base. Arrays are declared by specifying the upper and lower bounds in a way similar to Pascal and Fortran. It is also possible to use the Option Base statement to set the default lower bound. Use of the Option Base statement can lead to confusion when reading Visual Basic code and is best avoided by always explicitly specifying the lower bound of the array. This lower bound is not limited to 0 or 1, because it can also be set by declaration. In this way, both the lower and upper bounds are programmable. In more subscript-limited languages, the lower bound of the array is not variable. This uncommon trait does exist in Visual Basic .NET but not in VBScript.

    OPTION BASE was introduced by ANSI, with the standard for ANSI Minimal BASIC in the late 1970s.

    * Relatively strong integration with the Windows operating system and the Component Object Model.
    * Banker's rounding as the default behavior when converting real numbers to integers with the Round function.
    * Integers are automatically promoted to reals in expressions involving the normal division operator (/) so that division of an odd integer by an even integer produces the intuitively correct result. There is a specific integer divide operator (\) which does truncate.
    * By default, if a variable has not been declared or if no type declaration character is specified, the variable is of type Variant. However this can be changed with Deftype statements such as DefInt, DefBool, DefVar, DefObj, DefStr. There are 12 Deftype statements in total offered by Visual Basic 6.0. The default type may be overridden for a specific declaration by using a special suffix character on the variable name (# for Double, ! for Single, & for Long, % for Integer, $ for String, and @ for Currency) or using the key phrase As (type). VB can also be set in a mode that only explicitly declared variables can be used with the command Option Explicit.

 

Evolution of Visual Basic

VB 1.0 was introduced in 1991. The drag and drop design for creating the user interface is derived from a prototype form generator developed by Alan Cooper and his company called Tripod. Microsoft contracted with Cooper and his associates to develop Tripod into a programmable form system for Windows 3.0, under the code name Ruby (no relation to the Ruby programming language).

Tripod did not include a programming language at all. Microsoft decided to combine Ruby with the Basic language to create Visual Basic.

The Ruby interface generator provided the "visual" part of Visual Basic and this was combined with the "EB" Embedded BASIC engine designed for Microsoft's abandoned "Omega" database system. Ruby also provided the ability to load dynamic link libraries containing additional controls (then called "gizmos"), which later became the VBX interface[5].

Timeline of Visual Basic (VB1 to VB6)

    * Project 'Thunder' was initiated
    * Visual Basic 1.0 (May 1991) was released for Windows at the Comdex/Windows World trade show in Atlanta, Georgia.

VB DOS Logo
Visual Basic for MS-DOS

    * Visual Basic 1.0 for DOS was released in September 1992. The language itself was not quite compatible with Visual Basic for Windows, as it was actually the next version of Microsoft's DOS-based BASIC compilers, QuickBASIC and BASIC Professional Development System. The interface used the "COW" (Character Oriented Windows) interface, using extended ASCII characters to simulate the appearance of a GUI.
    * Visual Basic 2.0 was released in November 1992. The programming environment was easier to use, and its speed was improved. Notably, forms became instantiable objects, thus laying the foundational concepts of class modules as were later offered in VB4.
    * Visual Basic 3.0 was released in the summer of 1993 and came in Standard and Professional versions. VB3 included version 1.1 of the Microsoft Jet Database Engine that could read and write Jet (or Access) 1.x databases.
    * Visual Basic 4.0 (August 1995) was the first version that could create 32-bit as well as 16-bit Windows programs. It also introduced the ability to write non-GUI classes in Visual Basic. Incompatibilities between different releases of VB4 caused installation and operation problems. While previous versions of Visual Basic had used VBX controls, Visual Basic now used OLE controls (with files names ending in .OCX) instead. These were later to be named ActiveX controls.
    * With version 5.0 (February 1997), Microsoft released Visual Basic exclusively for 32-bit versions of Windows. Programmers who preferred to write 16-bit programs were able to import programs written in Visual Basic 4.0 to Visual Basic 5.0, and Visual Basic 5.0 programs can easily be converted with Visual Basic 4.0. Visual Basic 5.0 also introduced the ability to create custom user controls, as well as the ability to compile to native Windows executable code, speeding up calculation-intensive code execution. A free, downloadable Control Creation Edition was also released for creation of ActiveX controls. It was also used as an introductory form of Visual Basic: a regular .exe project could be created and run in the IDE, but not compiled.
    * Visual Basic 6.0 (Mid 1998) improved in a number of areas [6] including the ability to create web-based applications. VB6 has entered Microsoft's "non-supported phase" as of March 2008. Although the Visual Basic 6.0 development environment is no longer supported, the runtime is supported on Windows Vista, Windows Server 2008 and Windows 7 [7].
    * Mainstream Support for Microsoft Visual Basic 6.0 ended on March 31, 2005. Extended support ended in March 2008.[8] In response, the Visual Basic user community expressed its grave concern and lobbied users to sign a petition to keep the product alive.[9] Microsoft has so far refused to change their position on the matter. (but see [10]) Ironically, around this time (2005), it was exposed that Microsoft's new anti-spyware offering, Microsoft AntiSpyware (part of the GIANT Company Software purchase), was coded in Visual Basic 6.0.[11]Its replacement, Windows Defender, was rewritten as C++ code.[12]

Derivative languages

Microsoft has developed derivatives of Visual Basic for use in scripting. Visual Basic itself is derived heavily from BASIC, and subsequently has been replaced with a .NET platform version.

Some of the derived languages are:

    * Visual Basic for Applications (VBA) is included in many Microsoft applications (Microsoft Office), and also in many third-party products like SolidWorks, AutoCAD, WordPerfect Office 2002, ArcGIS and Sage Accpac ERP. There are small inconsistencies in the way VBA is implemented in different applications, but it is largely the same language as VB6 and uses the same runtime library.
    * VBScript is the default language for Active Server Pages. It can be used in Windows scripting and client-side web page scripting. Although it resembles VB in syntax, it is a separate language and it is executed by vbscript.dll as opposed to the VB runtime. ASP and VBScript should not be confused with ASP.NET which uses the .NET Framework for compiled web pages.
    * Visual Basic .NET is Microsoft's designated successor to Visual Basic 6.0, and is part of Microsoft's .NET platform. Visual Basic.Net compiles and runs using the .NET Framework. It is not backwards compatible with VB6. An automated conversion tool exists, but fully automated conversion for most projects is impossible.[13]
    * Star Basic is a Visual Basic compatible interpreter included in StarOffice suite, developed by Sun Microsystems.
    * Gambas is a Visual Basic inspired free software programming language for GNU/Linux. It is not a clone of Visual Basic, but it does have the ability to convert Visual Basic programs to Gambas.
    * KBasic is a Visual Basic inspired free software programming language for Linux, Mac and Windows. It is not a clone of Visual Basic, but it does have the ability to convert Visual Basic programs to KBasic.

Performance and other issues

Earlier counterparts of Visual Basic (prior to version 5) compiled the code to P-Code or Pseudo code only. Visual Basic 5 and 6 are able to compile the code to either native or P-Code as the programmer chooses. The P-Code is interpreted by the language runtime, also known as virtual machine, implemented for benefits such as portability and small code. However, it usually slows down the execution by adding an additional layer of interpretation of code by the runtime although small amounts of code and algorithms can be constructed to run faster than the compiled native code. Visual Basic applications require Microsoft Visual Basic runtime MSVBVMxx.DLL, where xx is the relevant version number, either 50 or 60. MSVBVM60.dll comes as standard with Windows in all editions after Windows 98 while MSVBVM50.dll comes with all editions after Windows 95. A Windows 95 machine would however require inclusion with the installer of whichever dll was needed by the program.

Other criticisms levelled at Visual Basic editions prior to VB.NET include:[14]

    * Versioning problems associated with various runtime DLL's (see DLL hell)
    * Poor support for object-oriented programming[15]
    * Inability to create multi-threaded applications, without resorting to Windows API calls
    * Lack of unicode support
    * Inability to create Windows services
    * Inability to create console applications
    * Variant types have a greater performance and storage overhead than strongly-typed programming languages

Legacy development and support

All versions of Visual Basic from 1.0 to 6.0 have been retired and are now unsupported by Microsoft. Visual Basic 6 programs can still run on Windows versions up to and including Vista, Windows Server 2008 and Windows 7, and the runtime is supported by Microsoft on these versions.[16]. Development and maintenance development for Visual Basic 6 is possible on Windows XP and Windows 2003 using Visual Studio 6.0. Documentation for Visual Basic 6.0, its application programming interface and tools is best covered in the last MSDN release before Visual Studio.NET 2002. Later releases of MSDN focused on .NET development and had significant parts of the Visual Basic 6.0 programming documentation removed. Development for this type of legacy system is typically done using a virtual machine with Windows 2003 or Windows XP, Visual Studio 6.0 and MSDN documentation. As of August 2008, both Visual Studio 6.0 and the MSDN documentation mentioned above are available for download by MSDN subscribers.

Example code

Here is an example of the language: Code snippet that display a message box "Hello, World!" as the window Form loads:

Private Sub Form_Load()
    MsgBox "Hello, World!"
End Sub

For more details on this topic, see Wikibooks:Visual Basic.

Read More..

Creating a Windows DLL with Visual Basic Part II

Let's begin by creating an ActiveX DLL project and seeing what happens if we try to call it as if it were a standard Windows DLL. When you create an ActiveX DLL project, Visual Basic automatically adds a class module (a .cls file) to it. You can rename this if you want, but don't include any code. Instead, add a code module (a .bas file) to the project, add the DLL's code, and then compile the DLL. When you run the DLL test application, the error message dialog shown in Figure 1 appears. The error message indicates that although the DLL was found, the specific called function (Increment) was not.

>Error when accessing an ActiveX DLL as a Windows DLL
The most likely cause of this error is that the function is not actually exported by the DLL. We can use the DumpBin utility to examine a DLL's exports by using the syntax

Dumpbin <path and name of dll> /exports

If we run DumpBin using this syntax, we see the following output:

Microsoft (R) COFF Binary File Dumper Version 6.00.8447
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.

Dump of file mathlib.dll

File Type: DLL

  Section contains the following exports for MathLib.dll

           0 characteristics
    41B9E52C time date stamp Fri Dec 10 10:04:28 2004
        0.00 version
           1 ordinal base
           4 number of functions
           4 number of names

    ordinal hint RVA      name

          1    0 0000192E DllCanUnloadNow
          2    1 00001902 DllGetClassObject
          3    2 00001918 DllRegisterServer
          4    3 000018EC DllUnregisterServer

  Summary

        1000 .data
        1000 .reloc
        1000 .rsrc
        1000 .text

Our DLL exports four functions, all of which are utility functions that support COM. Clearly we need to export DllMain and our three math functions. But how? Visual Basic does not appear to allow you to export DLL functions from ActiveX DLLs, thus effectively preventing you from using Visual Basic to create a standard Windows DLL.

This difficulty, however, is not insurmountable. When we select the File -> Make <filename>.dll menu option to create an ActiveX DLL, it appears that Visual Basic is seamlessly taking our source code and outputting an ActiveX DLL. But if we examine the subdirectory in which Visual Basic was installed, it appears that the process is not quite so seamless. Along with VB6.EXE, the Visual Basic executable that defines the Visual Basic environment, we can also find C2.EXE and LINK.EXE, which are a compiler and a linker, respectively. Their presence in this directory suggests that VB6.EXE itself does not handle the generation of a DLL file, but that at some point in the compilation process, it calls these programs.

We can find out how Visual Basic is using the compiler and linker more precisely by renaming them and creating wrapper executables named C2 and LINK that in turn call the real compiler and linker. The following is the source code for a new version of a console-mode C2.EXE that calls the "real" C2 compiler, which we've renamed C2comp.exe:

Public Sub Main()

On Error Resume Next

   Dim strCmd As String, strPath As String
   Dim oFS As New Scripting.FileSystemObject
   Dim ts As TextStream

   strCmd = Command
   strPath = App.Path
   Set ts = oFS.CreateTextFile(strPath & "\c2log.txt")
   ts.WriteLine "Beginning execution at " & Date & " " & Time()
   ts.WriteBlankLines 1
   ts.WriteLine "Command line parameters to c2 call:"
   ts.WriteLine "   " & strCmd
   ts.WriteBlankLines 1
   ts.WriteLine "Calling C2 compiler"
   Shell "c2comp.exe " & strCmd
   If Err.Number <> 0 Then
      ts.WriteLine "Error in calling C2 compiler..."
   End If
   ts.WriteBlankLines 1
   ts.WriteLine "Returned from c2 compiler call"
   ts.Close
End Sub

The process of compiling an ActiveX DLL produces the following output in our log file:

Beginning execution at 12/10/2004 12:44:22 PM

Command line parameters to c2 call:
   -il "C:\DOCUME~1\Ron\LOCALS~1\Temp\VB277103" -f "C:\VB Projects\
   MathLib\MathMod.bas" -W 3 -Gy -G5 -Gs4096 -dos -Zl -Fo"C:\
   VB Projects\MathLib\MathMod.OBJ" -QIfdiv -ML -basic

Calling C2 compiler

Returned from c2 compiler call

These are fairly standard command-line arguments to produce object files that in turn are supplied to the linker. That means that to determine how to produce a Windows DLL, we'll have to intercept the call to the linker so that we can see what arguments Visual Basic passes to it. The following code does that:

Public Sub Main()

On Error Resume Next

   Dim strCmd As String, strPath As String
   Dim oFS As New Scripting.FileSystemObject
   Dim ts As TextStream

   strCmd = Command
   strPath = App.Path
   Set ts = oFS.CreateTextFile(strPath & "\lnklog.txt")
   ts.WriteLine "Beginning execution at " & Date & " " & Time()
   ts.WriteBlankLines 1
   ts.WriteLine "Command line parameters to LINK call:"
   ts.WriteLine "   " & strCmd
   ts.WriteBlankLines 1
   ts.WriteLine "Calling LINK linker"
   Shell "linklnk.exe " & strCmd
   If Err.Number <> 0 Then
      ts.WriteLine "Error in calling linker..."
      Err.Clear
   End If
   ts.WriteBlankLines 1
   ts.WriteLine "Returned from linker call"
   ts.Close
End Sub

It requires that we rename the linker LinkLnk.exe and name our link wrapper Link.exe.

When we attempt to compile an ActiveX DLL project, our linker log file contains the following output:

Beginning execution at 12/11/2004 12:44:33 PM

Command line parameters to LINK call:
   "C:\Program Files\Microsoft Visual Studio\VB98\Class1.OBJ"
   "C:\Program Files\Microsoft Visual Studio\VB98\Project1.OBJ"
   "C:\Program Files\Microsoft Visual Studio\VB98\VBAEXE6.LIB"
   /ENTRY:__vbaS
   /OUT:"C:\Program Files\Microsoft Visual Studio\VB98\Project1.dll"
   /BASE:0x11000000
   /SUBSYSTEM:WINDOWS,4.0 /VERSION:1.0
   /DLL 
   /INCREMENTAL:NO /OPT:REF /MERGE:.rdata=.text /IGNORE:4078

Calling LINK linker

Returned from linker call

If we compare these command-line arguments with the syntax required to link the object files for a DLL using either C or C++, an omission becomes immediately apparent. Although the /DLL switch is supplied to create a standard DLL, there is no /DEF switch to define a module definition (.def) file that lists the functions exported by the DLL. (If we were programming in C or C++, we could use statements within our code to define our exports. Visual Basic doesn't support this, however, making the .def file the sole means of defining a library's exports.) Moreover, if we examine the files generated for an ActiveX DLL project by the Visual Basic environment, we'll also find that Visual Basic itself has not generated a .def file.

Read More..

Creating a Window DLL With Visual Basic Part III

So, after examining an ActiveX DLL's export table, intercepting Visual Basic's call to the compiler, intercepting Visual Basic's call to the linker, and comparing the arguments passed to the linker with those required by a C/C++ compiler to generate a Windows DLL, we've finally identified why we aren't able to successfully create a Windows DLL with Visual Basic. And fortunately, we can work around that restriction. We should be able to create a standard Windows DLL if we do the following:

   1. Create a .def file for our project. We can specify our exported functions in the .def file in several ways, but it's best to keep it simple:

      NAME MathLib
      LIBRARY MathMod
      DESCRIPTION "Add-on Library of Mathematical Routines"
      EXPORTS DllMain @1
              Increment @2
              Decrement @3
              Square @4

      The NAME statement defines the name of the DLL. The LIBRARY statement must either precede the list of exported functions or appear on the same line as the first function. The .def file should also list the ordinal position of each exported function preceded by an @ symbol.


   2. Decide how we want to intercept the call to the linker. Two major techniques are available to do this:
          *

            Patching the Import Address Table (IAT), which requires that we build a Visual Basic add-in that modifies the IAT in order to intercept particular calls by Visual Basic to the Win32 API. Although it's certainly the most elegant method, its complexity makes it a worthy subject for a separate article.
          *

            Building a proxy linker that intercepts the call to the real linker, modifies the command-line arguments to be passed to the linker, and then calls the linker with the correct command-line arguments. This is the approach we used to discover what arguments Visual Basic was passing to the compiler and linker, and it's the approach we'll adopt to create a Windows DLL.

      In building our proxy linker, we want a sufficiently flexible design so that we can generate other kinds of files, if need be.


   3.   Modify the arguments to the linker to add the /DEF switch along with the path and filename of our .def file. To do this, you must create a Visual Basic Standard EXE project, add a reference to the Microsoft Scripting Runtime Library, remove the form from the project, and add a code module. The source code for the proxy linker is as follows:

      Option Explicit

      Public Sub Main()

         Dim SpecialLink As Boolean, fCPL As Boolean, fResource As Boolean
         Dim intPos As Integer
         Dim strCmd As String
         Dim strPath As String
         Dim strFileContents As String
         Dim strDefFile As String, strResFile As String
         Dim oFS As New Scripting.FileSystemObject
         Dim fld As Folder
         Dim fil As File
         Dim ts As TextStream, tsDef As TextStream

         strCmd = Command
         Set ts = oFS.CreateTextFile(App.Path & "\lnklog.txt")
         ts.WriteLine "Beginning execution at " & Date & " " & Time()
         ts.WriteBlankLines 1
         ts.WriteLine "Command line arguments to LINK call:"
         ts.WriteBlankLines 1
         ts.WriteLine "   " & strCmd
         ts.WriteBlankLines 2
         ' Determine if .DEF file exists
         '
         ' Extract path from first .obj argument
         intPos = InStr(1, strCmd, ".OBJ", vbTextCompare)
         strPath = Mid(strCmd, 2, intPos + 2)
         intPos = InStrRev(strPath, "\")
         strPath = Left(strPath, intPos - 1)
         ' Open folder
         Set fld = oFS.GetFolder(strPath)
         ' Get files in folder
         For Each fil In fld.Files
            If UCase(oFS.GetExtensionName(fil)) = "DEF" Then
               strDefFile = fil
               SpecialLink = True
            End If
            If UCase(oFS.GetExtensionName(fil)) = "RES" Then
               strResFile = fil
               fResource = True
            End If
            If SpecialLink And fResource Then Exit For
         Next
         ' Change command line arguments if flag set
         If SpecialLink Then
            ' Determine contents of .DEF file
            Set tsDef = oFS.OpenTextFile(strDefFile)
            strFileContents = tsDef.ReadAll
            If InStr(1, strFileContents, "CplApplet", vbTextCompare) > 0 Then
               fCPL = True
            End If
            ' Add module definition before /DLL switch
            intPos = InStr(1, strCmd, "/DLL", vbTextCompare)
            If intPos > 0 Then
               strCmd = Left(strCmd, intPos - 1) & _
                     " /DEF:" & Chr(34) & strDefFile & Chr(34) & " " & _
                     Mid(strCmd, intPos)
            End If
            ' Include .RES file if one exists
            If fResource Then
               intPos = InStr(1, strCmd, "/ENTRY", vbTextCompare)
               strCmd = Left(strCmd, intPos - 1) & Chr(34) & strResFile & _
                        Chr(34) & " " & Mid(strCmd, intPos)
            End If
            ' If Control Panel applet, change "DLL" extension to "CPL"
            If fCPL Then
               strCmd = Replace(strCmd, ".dll", ".cpl", 1, , vbTextCompare)
            End If
            ' Write linker options to output file
            ts.WriteLine "Command line arguments after modification:"
            ts.WriteBlankLines 1
            ts.WriteLine "   " & strCmd
            ts.WriteBlankLines 2
         End If
         ts.WriteLine "Calling LINK.EXE linker"
         Shell "linklnk.exe " & strCmd
         If Err.Number <> 0 Then
            ts.WriteLine "Error in calling linker..."
            Err.Clear
         End If
         ts.WriteBlankLines 1
         ts.WriteLine "Returned from linker call"
         ts.Close
      End Sub

      This proxy linker modifies only the command-line arguments passed to the linker if a .def file is present in the directory that contains the Visual Basic project; otherwise it simply passes the command-line arguments on to the linker unchanged. If a .def file is present, it adds a /DEF switch to the command line. It also determines whether any resource files are to be added to the linked file list. Finally, it examines the export table to determine if a function named CplApplet is present; if it is, it changes the output file's extension from .dll to .cpl.
  

4.  To install the proxy linker, rename the original Visual Basic linker LinkLnk.exe, copy the proxy linker to the Visual Basic directory, and name it Link.exe.

Once we create our proxy linker, we can reload our MathLib project and compile it into a DLL by selecting the Make MathLib.exe option from the File menu.
Testing the DLL

Once we create our Windows DLL, the final step is to test it to make sure that it works. To do this, create a new Standard EXE project (let's call it MathLibTest) and add a code module. To make sure that code in our project can access the functions exported by the DLL, we use the standard Visual Basic Declare statement. We declare our three exported math routines in the code module as follows:

Option Explicit

Public Declare Function Increment Lib "C:\VBProjects\MathLib\mathlib.dll" ( _
                        value As Integer) As Integer
Public Declare Function Decrement Lib "C:\VBProjects\MathLib\mathlib.dll" ( _
                        value As Integer) As Integer
Public Declare Function Square Lib "C:\VBProjects\MathLib\mathlib.dll" ( _
                        value As Long) As Long

We can then use the following code in the form module to call the routines in the DLL:

Option Explicit

Private Sub cmdDecrement_Click()
   txtDecrement.Text = Decrement(CInt(txtDecrement.Text))
End Sub

Private Sub cmdIncrement_Click()
   txtIncrement.Text = Increment(CInt(txtIncrement.Text))
End Sub

Private Sub cmdSquare_Click()
   txtSquare.Text = Square(CLng(txtSquare.Text))
End Sub

Private Sub Form_Load()
   txtIncrement.Text = 0
   txtDecrement.Text = 100
   txtSquare.Text = 2
End Sub

When we call each of the MathLib functions, the application window might appear as it does in Figure 2, confirming that the calls to the MathLib routines work as expected.

Read More..