Visual Basic - Application Programming Interface
Dynamic Link Libraries
Windows has many in-built functions that we haven’t yet used and these functions are defined in libraries, which are called as Dynamic Link Libraries (DLL’s). These libraries are defined in \windows\system directory. And the pre-defined functions in DLL are called as Application Programming Interface (API).
Let’s have a look at commonly available DLLs
Table 1: DLL’s supported by Windows
Sr. No |
DLL |
Applications it supports |
1 |
Advapi32.dll |
Security & Registry Calls |
2 |
Comdlg32.dll |
Common Dialog API Library |
3 |
Gdi32.dll |
Graphics Device Interface |
4 |
Kernel32.dll |
32-bit Windows applications |
5 |
Lz32.dll |
32-bit Compression Routines |
6 |
Mpr.dll |
Multiple Provider Router |
7 |
Shell32.dll |
32-bit Shell applications |
8 |
User32.dll |
User Interface Routines |
9 |
Version.dll |
Version Library |
10 |
Winmm.dll |
Multimedia Programming |
Windows makes our task a bit easier by not letting us remember the names of DLL’s. These DLL’s are directly called by API. So, we need to understand how to use the functions of API. Before we proceed to use of API functions, let’s first have a look to how to view the functions in API through API Viewer (a tool provided with Microsoft Visual Studio.)
Figure 1: API Viewer - Win32api.txt
Let’s see the item: SetCapture in order to understand the structure of an API call.
Public Declare Function SetCapture Lib "user32" Alias "SetCapture" (ByVal hwnd As Long) As Long
Let’s understand the syntax of the function:
Table 2: Syntax of SetCapture
Function Name |
SetCapture |
Actual Windows Function Name |
SetCapture (written after Alias) |
DLL |
User32 |
Argument: |
|
hwnd |
Handle of the Window |
Creating Device Context
What is Device Context
A device context is a Windows data structure containing information about the drawing attributes of a device such as a display or a printer. All drawing calls are made through a device-context object, which encapsulates the Windows APIs for drawing lines, shapes, and text. Device contexts allow device-independent drawing in Windows. Device contexts can be used to draw to the screen, to the printer, or to a metafile.
Device Context and API Calls
Each of the Visual Basic Controls has an hDC property, which holds their device context. We can also get a device context for a window using GetDC, which on success returns handle to device context and on unsuccessful attempt, returns zero. Similarly, to create a device context for a device, we can use CreateDC function.
Public Declare Function GetDC Lib "user32" Alias "GetDC" (ByVal hwnd As Long) As Long
Public Declare Function CreateDC Lib "gdi32" Alias "CreateDCA" (ByVal lpDriverName As String, ByVal lpDeviceName As String, ByVal lpOutput As String, lpInitData As DEVMODE) As Long
Let’s first understand the arguments of both of these.
Table 3: Arguments of CreateDC
Argument |
Interpretation |
lpDriverName |
This string specifies the filename of the device driver. |
lpDeviceName |
Name of specific device to be supported. |
lpOutput |
Output file or Device Name. |
lpInitData |
This string defines device-specific configuration. This parameter is null to use default Initialization, else required configuration is provided. |
We shall not be using Device Context in our application but one should have its knowledge while programming graphics.
Capturing Mouse Motion on Screen
Defining Application Problem
In this application, our focus is to capture the motion of the mouse. On pressing the Record Button, the motion tracking starts and this stops on pressing Stop Button. We can view the motion by pressing Play Button.
Understanding API
Let’s quickly review the different API functions we shall use in our screen capture program. The Syntax and their function is written in Table 4.
Table 4: API’s used in application
DLL |
API Function |
Syntax |
Purpose |
User32 |
GetCursorPos |
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
|
Retrieves the cursor's position, in screen coordinates. |
SetCursorPos |
Private Declare Function SetCursorPos Lib "user32" (ByVal X As Long, ByVal Y As Long) As Long
|
Moves the cursor to the specified screen coordinates. |
|
Kernel32 |
Sleep |
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) |
The Sleep function suspends the execution of the current thread for at least the specified interval.
|
Here, POINTAPI needs to defined as,
Private Type POINTAPI
X As Long
Y As Long
End Type
Application Design
In this application, we use following tools:
Table 5: Controls Used in Application
Controls |
No Of Times Used |
Name |
Command Buttons |
5 |
cmdRecord cmdStop cmdPlay |
ScrollBar |
1 |
hscrlSpeed |
Label |
1 |
lblSpeed |
Timer |
1 |
tmrMouse |
The crux of the program lies in programming the timer.
Private I As Long
Private sMouseArray() As String
Private Function RecordMouse() As String
Dim mouse As POINTAPI
GetCursorPos mouse
RecordMouse = mouse.X & " " & mouse.Y
End Function
Private Sub tmrMouse_Timer()
ReDim Preserve sMouseArray(I)
sMouseArray(I) = RecordMouse
I = I + 1
End Sub
In the above code, RecordMouse is a function in which the current position of mouse is obtained. RecordMouse is called in 2nd line of tmrMouse. In this function, the current position of mouse is stored in sMouseArray. sMouseArray and I are global variables.
The second important part of the application is to Play the motion of the mouse from the sMouseArray.
Private Sub cmdPlay_Click()
Dim J, lPlay, lX, lY As Long
Dim sSplit() As String
lPlay = I
For J = 1 To lPlay
sSplit = Split(sMouseArray(J - 1))
lX = CLng(sSplit(0))
lY = CLng(sSplit(1))
Sleep hscrlSpeed.Value
SetCursorPos lX, lY
Next J
End Sub
Figure 2: Mouse Tracer
Initially IPlay contains the total number of elements in sMouseArray. sSplit contains the one group of values of mouse position defined as “X Y”. lX and lY contain X and Y values respectively. A break or a sleep period is provided as per delay adjusted by the horizontal scrollbar. The mouse cursor is set to those coordinates by use of SetCursorPos.
The New button acts like a reset button and prepares the system to capture the new movement of the mouse, erasing the previous record. We code it as below:
Private Sub cmdNew_Click()
cmdStop.Enabled = False
tmrMouse.Enabled = False
cmdRecord.Enabled = True
cmdPlay.Enabled = False
I = 0
End Sub
Similarly the Record button indirectly calls the RecordMouse () function by enabling the tmrMouse, which enables us to start the recording procedure.
Private Sub cmdRecord_Click()
cmdStop.Enabled = True
tmrMouse.Enabled = True
cmdRecord.Enabled = False
cmdNew.Enabled = False
End Sub
To stop the recording procedure, we need to click on the Stop button. This enables the play button enabling us to view the movement as many times as we want.
Private Sub cmdStop_Click()
cmdStop.Enabled = False
tmrMouse.Enabled = False
cmdPlay.Enabled = True
cmdNew.Enabled = True
End Sub
Controlling Windows Shutdown through API
Let’s understand one more API function, ExitWindowsEx. This function helps us to shutdown, log off or restart our computer.
Defining Application Problem
The user selects one of the options from Shutdown, Restart or Log Off and provides with number of minutes after which the computer should either Shutdown, Restart or Log Off.
Understanding API
Public Declare Function ExitWindowsEx Lib "user32" Alias "ExitWindowsEx" (ByVal uFlags As Long, ByVal dwReserved As Long) As Long
Let’s understand the syntax of this function and then see an application example.
Table 6: Syntax of ExitWindowsEx
Function Name: |
ExitWindowsEx |
||||||||||
Actual Windows Function Name: |
ExitWindowsEx |
||||||||||
Arguments: |
|||||||||||
uFlags |
|
||||||||||
dwReserved |
Reason for initiating the shutdown. This parameter must be one of the system shutdown reason codes. Since we would like to shutdown for application purpose, we use the code 0x00040000
|
Table 7: Some of the System Codes for dwReserved
Code |
Purpose |
SHTDN_REASON_MAJOR_APPLICATION |
Application issue. |
SHTDN_REASON_MAJOR_HARDWARE |
Hardware issue. |
SHTDN_REASON_MAJOR_LEGACY_API |
The InitiateSystemShutdown function was used instead of InitiateSystemShutdownEx. |
SHTDN_REASON_MAJOR_OPERATINGSYSTEM |
Operating system issue. |
SHTDN_REASON_MAJOR_OTHER |
Other issue. |
SHTDN_REASON_MAJOR_POWER |
Power failure. |
SHTDN_REASON_MAJOR_SOFTWARE |
Software issue. |
SHTDN_REASON_MAJOR_SYSTEM |
System failure. |
Application Design
Let’s analyze the code.
Global declarations that follow are:
Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags&, ByVal wReserved&)
Const EWX_FORCE = 4
Const EWX_LOGOFF = 0
Const EWX_REBOOT = 2
Const EWX_SHUTDOWN = 1
Public Choice, TimeRequired
The code for starting to Log Off, Shutdown or Restart when user presses Apply Button is as:
Private Sub cmdApply_Click()
Timer1.Enabled = True
Timer1.Interval = 1000
tvalue = Val(Text1.Text) * 60
'convert minutes to seconds
TimeRequired = tvalue
OptLogOff.Enabled = False
OptShutdown.Enabled = False
OptRestart.Enabled = False
CmdApply.Enabled = False
Text1.Enabled = False
MsgBox "Timer Starts Now!"
End Sub
Private Sub cmdCancel_Click()
CmdApply.Enabled = True
Timer1.Enabled = False
End
End Sub
To avoid automatic action when the form loads, we provide the following code:
Private Sub Form_Load()
OptLogOff.Value = False
OptShutdown.Value = False
OptRestart.Value = False
End Sub
Private Sub OptLogOff_Click() ‘Log Off
CmdApply.Enabled = True
If OptLogOff.Value = True Then
Choice = EWX_LOGOFF 'user chooses to logoff
End If
End Sub
Private Sub OptShutdown_Click() ‘Shutdown
CmdApply.Enabled = True
If OptShutdown.Value = True Then
Choice = EWX_SHUTDOWN 'user chooses to shutdown
End If
End Sub
Private Sub OptRestart_Click() ‘Reboot
CmdApply.Enabled = True
If OptRestart.Value = True Then
Choice = EWX_REBOOT 'user chooses to restart
End If
End Sub
The most important part where the API function is called is Timer.
Private Sub Timer1_Timer()
Static Counter
If Counter <> TimeRequired Then
Counter = Counter + 1
'increment our counter if it is not yet time
Else
vResult = ExitWindowsEx(Choice, 0&)
Counter = 0
End
End If
End Sub
Figure 3: Windows Shutter
The final application after programming appears as shown in Figure 3. There are various other examples of API such as Graphics Programming, Playing Sounds, Setting up Registry Values, Capturing Screen, Capturing Web cam and many more.
In our next article in this issue, we focus on Multimedia Programming and consider few applications.
Note: This series was first published in DeveloperIQ and was co-authored by Puneet Ghanshani with Pranjali Bakeri in 2005-2006.