Windows API

Using Windows API

Once you have declared your Windows API function, you need to be able to use it.   Windows API functions take a number of different formats. The simplest one is a DLL that just does something, and does not return any strings or pointers. An example is provided below:

'// DLL declarations and constants
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Const WM_UNDO = &H304 ' Undos the last action (Ctrl+Z)

'// Command Button Event
Sub cmdUndo_Click()
    SendMessage(txtText.hWnd, WM_UNDO, 0, 0& )
End Sub

If you want more information on using the SendMessage api function, see the Sending Messages article.

Another common function is one that returns a string which contains text. The following example shows you how to create a function that will get the Windows directory.

'// DLL declarations and constants
Private Declare Function GetWindowsDirectory Lib "kernel32" Alias "GetWindowsDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Long) As Long
Const MAX_PATH As Integer = 260

'// Get Windows Directory function
Public Function GetWindowsDir() As String
    Dim strWinDir As String '// String that will contain win path
    Dim lngResult As Long '// Long Variable that will contain the result value (success/fail)
    '// Fill the Windows dir variable with 260 spaces (259 is the maximum path length, with one space for the trailing null)
    '// if you do not give enough space, you will not get anything at all.
    strWinDir = Space(MAX_PATH)
    '// Call the function, and get the result. We pass the strWinDir variable as a parameter,
    '// this way the DLL can fill it with the result. The last parameter specifies the length of the string
    lngResult = GetWindowsDirectory(strWinDir, MAX_PATH)
    '// suceeded?
    If lngResult = 0 Then
        '// failed, return nothing
        GetWindowsDir = vbNull
    Else
        '// successful, trim result string and return it
        GetWindowsDir = Trim(strWinDir)
    End If
End Function

Other Windows API declarations are more complex, and the best way to learn is to download some code from the VB Component section, and examine it yourself.

You might also like...

Comments

About the author

James Crowley

James Crowley United Kingdom

James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audien...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“It works on my machine.” - Anonymous