API Tip

Obtain Windows and System Directory

 All of your applications written with VB are run in Windows (r) (tm) environment. Since that's the case, very often we need to determine Windows directory  (c:\windows - typical for Win9x machines, Winnt - typical for 2000, XP) and system directory. To do just that is very easy using two API calls with very intuitive names: GetWindowsDirectory and GetSystemDirectory. Here are their declarations:

Public Declare Function GetWindowsDirectory Lib "kernel32" Alias "GetWindowsDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Long) As Long

Public Declare Function GetSystemDirectory Lib "kernel32" Alias "GetSystemDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Long) As Long

Once you have these functions declared, the rest is easy. Here is the example of how to obtain system directory (first function is declared and then used in a Sub)::

Private Declare Function GetWindowsDirectory Lib "kernel32" Alias "GetWindowsDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Long) As Long

Private Sub cmdGetSysDir_Click()

Dim rc As Long
Dim buff As String 'buffer to store system path

   buff = Space$(255) 'allocate enough space

   rc = GetSystemDirectory(buff, 255) 'call API

   If rc <> 0 Then 'if success
      MsgBox Left$(buff, rc), , "Info"  'message box with directory
   Else
      txtSysDir.Text = "Unsuccesful'"
   End If

End Sub

In a few lines you have a complete and correct system path which you can use as you wish (store dlls or search for some files, etc.)
Be sure to save your work before you mess around with Windows (r) API, some behavior of these functions is unpredictable. Just a friendly warning.

Api Tips - Home

          

Written By Laimonas Simutis. 2002. mailto:\\laijerrad@yahoo.com